我曾经使用过socket对象来进行编程(而不是TCP客户端)。我创建了一个类似于以下代码的Server对象(为了简洁,我省略了一些东西,如异常处理,但我希望这个想法能够通过)...
public class Server()
{
private Socket sock;
private int port = 8080;
private IPAddress addr = IPAddress.Any;
public void Start()
{
this.sock = new Socket(
addr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
sock.Bind(new IPEndPoint(this.addr, this.port));
this.sock.Listen(this.backlog);
this.sock.BeginAccept(this.OnConnectRequest, sock);
}
private void OnConnectRequest(IAsyncResult result)
{
Socket sock = (Socket)result.AsyncState;
Connection newConn = new Connection(sock.EndAccept(result));
sock.BeginAccept(this.OnConnectRequest, sock);
}
}
然后,我使用一个单独的Connection类来管理与远程主机的个别连接。大致看起来像这样...
public class Connection()
{
private Socket sock;
private Encoding encoding = Encoding.UTF8;
public Connection(Socket s)
{
this.sock = s;
this.BeginReceive();
}
private void BeginReceive()
{
this.sock.BeginReceive(
this.dataRcvBuf, 0,
this.dataRcvBuf.Length,
SocketFlags.None,
new AsyncCallback(this.OnBytesReceived),
this);
}
protected void OnBytesReceived(IAsyncResult result)
{
int nBytesRec = this.sock.EndReceive(result);
if (nBytesRec <= 0)
{
this.sock.Close();
return;
}
string strReceived = this.encoding.GetString(
this.dataRcvBuf, 0, nBytesRec);
this.sock.BeginReceive(
this.dataRcvBuf, 0,
this.dataRcvBuf.Length,
SocketFlags.None,
new AsyncCallback(this.OnBytesReceived),
this);
}
}
您可以通过直接调用 Connection 对象的 Socket 来发送数据,方法如下...
this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));
正如我所说,我已经尝试编辑这里的代码以进行发布,因此如果有任何错误,请见谅。