In fact, as long as the use of socket connection, basically have to use thread, is cross use.
The socket usage of C # encapsulation is basically not very complicated, except that there is no other performance or security problem with the socket after hosting.
In C # can be found in the bottom of the operation is the socket, the concept does not explain.
The program model is as follows:
WinForm Program: Initiate port listening, monitor socket join, and periodically close inactive joins;
Listener: Handles the accept functions of the socket, listens for new links, and creates new thread to handle these joins (Connection).
Connection: handles each specific session of the join.
1:winform How to start a new thread to start the 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();
}
Because a listening join is a loop-waiting function, it is not possible to execute directly inside a WinForm thread, or WinForm is unable to continue any operation, so a new thread is specified to execute the function and start the listening loop.
This new thread is relatively simple and basically does not have a startup parameter, directly specifying the processing function is OK.
2:listener How to start circular listening and start a new thread with parameters to handle the socket join session.
First look at how to set up listening: (startlistening function)
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
……
}
}……