Welcome

首页 / 软件开发 / C# / C#的Socket程序(TCP)

C#的Socket程序(TCP)2011-03-12 cnblogs 随心所欲其实只要用到Socket联接,基本上就得使用Thread,是交叉使用的。

C#封装的Socket用法基本上不算很复杂,只是不知道托管之后的Socket有没有其他性能或者安全上的问题。

在C#里面能找到的最底层的操作也就是socket了,概念不做解释。

程序模型如下:

WinForm程序 : 启动端口侦听;监视Socket联接情况;定期关闭不活动的联接;

Listener:处理Socket的Accept函数,侦听新链接,建立新Thread来处理这些联接(Connection)。

Connection:处理具体的每一个联接的会话。

1:WinForm如何启动一个新的线程来启动Listener:

//start the server
private void btn_startServer_Click(object sender, EventArgs e)
{
//this.btn_startServer.Enabled = false;
Thread _createServer = new Thread(new ThreadStart(WaitForConnect));
_createServer.Start();
}
//wait all connections
private void WaitForConnect()
{
SocketListener listener = new SocketListener(Convert.ToInt32(this.txt_port.Text));
listener.StartListening();
}

因为侦听联接是一个循环等待的函数,所以不可能在WinForm的线程里面直接执行,不然Winform也就是无法继续任何操作了,所以才指定一个新的线程来执行这个函数,启动侦听循环。

这一个新的线程是比较简单的,基本上没有启动的参数,直接指定处理函数就可以了。

2:Listener如何启动循环侦听,并且启动新的带有参数的线程来处理Socket联接会话。

先看如何建立侦听:(StartListening函数)

IPEndPoint localEndPoint = new IPEndPoint(_ipAddress, _port);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(20);//20 trucks

// Start listening for connections.
while (true)
{
// here will be suspended while waiting for a new connection.
Socket connection = listener.Accept();
Logger.Log("Connect", connection.RemoteEndPoint.ToString());//log it, new connection
……
}
}……