. Net network programming -- the server obtains the Client Connection
1. Client Server connection Diagram
The connection information is reported in the socket between the client and the server. When the client connects through connect, the server can call AcceptTcpClient to obtain the client linked to the server, each client and server connection corresponds to this unique Socket.
2. server access example
Using System; using System. collections. generic; using System. linq; using System. text; using System. net; using System. net. sockets; namespace gets a single client connection {class Program {static void Main (string [] args) {# region gets a single client connection // Console. writeLine ("server startup .. "); // IPAddress ip = new IPAddress (new byte [] {127, 0, 0, 1}); // TcpListener listener = new TcpListener (ip, 8500 ); // listener. start (); // Console. writeLine ("the server starts listening for 8500 .... "); // Get a connection, interrupt method // TcpClient remoteClient = listener. acceptTcpClient (); // obtain a connection with the client, and return a TcpClient type example. In this case, it encapsulates the socket from the server to the client (this is a block method) //// print the information connected to the client // Console. writeLine ("client connection successful. Local: {0} ------> client {1} ", remoteClient. client. localEndPoint, remoteClient. client. remoteEndPoint); # endregion # region obtains the connection Console of multiple clients. writeLine ("server startup .. "); IPAddress ip = new IPAddress (new byte [] {127, 0, 0, 1}); TcpListener listener = new TcpListener (ip, 8500); listener. start (); Console. writeLine ("the server starts listening for 8500 .... "); While (true) {/* puts the server into a loop that is always executed. * /// Gets a connection. The disconnection method is TcpClient remoteClient = listener. acceptTcpClient (); // obtain a connection with the client, and return a TcpClient type example. In this case, it encapsulates the socket from the server to the client (this is a block method) // print the information Console that is connected to the client. writeLine ("client connection successful. Local: {0} ------> Client {1} ", remoteClient. Client. LocalEndPoint, remoteClient. Client. RemoteEndPoint) ;}# endregion }}}
PS: AcceptTcpClient is a synchronous method. Compared with AJAX Asynchronization, it can be found that if the server cannot obtain the client connection, it will always be blocked here, rather than when AJAX requests data, the following items can be continued, and then called back.