Original article: http://www.cnblogs.com/Elijah/archive/2011/11/29/2268047.html
Socket can be understood as an "Socket" composed of an IP address and a port "... it is true that this word is very vivid. With it, we are equivalent to setting a slot for the program, so other programs can "plug" in through the network ~
On the client side, we only need one Socket, but on the server side, we need to use a Socket to monitor a port, and then create a new Socket based on the client to communicate with each other.
The code is summarized as follows:
Server:
1 // 1. The server defines the Socket object used for listening:
2 Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
3 // set the IP address and port
4 IPAddress ip = IPAddress. Parse (ip address string );
5 IPEndPoint point = new IPEndPoint (ip, int. Parse (Port string ));
6 // bind the IP address and port to the Socket
7 socket. Bind (point );
8 // set the number of simultaneous queues
9 socket. Listen (count );
10
11 // 2. enable the new thread (Listen method) for listening:
12 Thread th = new Thread (Listen );
13 th. IsBackground = true;
14 th. Start ();
15
16 // 3. Loop listening in the new thread (in the Listen method:
17 while (true)
18 {
19 // create a new Socket called connect to listen to the IP address and port number of the socket
20 connect = socket. Accept ();
21 // enable the new thread (RecMsg method) for receiving messages
22 Thread th = new Thread (RecMsg );
23 th. IsBackground = true;
24 th. Start ();
25}
26
27 // 4. receive messages cyclically in the new thread (in the RecMsg method:
28 while (true)
29 {
30 byte [] buffer = new byte [length];
31 // If the connection is not closed
32 if (connect. Connected)
33 {
34 // use connect to receive messages and return the length of received messages
35 int length = connect. Receive (buffer );
36 // process or display messages
37 ....
38}
39}
Client:
1 // 1. The client defines the Socket object used to send information and connects to the server:
2 Socket client = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
3 IPAddress ip = IPAddress. Parse (Server ip address string );
4 IPEndPoint point = new IPEndPoint (ip, int. Parse (server port string ));
5 client. Connect (point );
6
7 // 2. Define the byte array buffer and send messages to the server:
8 client. Send (buffer );