Also, Socket and Socket
There are a large number of socket-related articles on the Internet, many of which are unclear. Recently, I sorted out socket-related knowledge and added a lotCode commentFirst look at the effect.
Code on,Client:
1 Socket socket1 = null; // a global socket object 2 3 private void btnConnect_Click (object sender, EventArgs e) 4 {5 // obtain the Server ip address and port number 6 IPAddress ip = IPAddress. parse (textBox1.Text); 7 int port = Convert. toInt32 (textBox2.Text); 8 9 // construct the client socket and set it to tcp mode 10 socket1 = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); 11 12 // connect 13 socket1.Connect (ip, port); 14 if (socket1.Connected) // If the connection is successful 15 {16 textBox3.Text + = "connection succeeded \ r \ n"; 17 SendMsg (socket1, "success"); 18 19 string recMsg = ""; 20 // receive 21 ReceiveMsg (socket1, ref recMsg); 22 textBox3.Text + = recMsg; // text display 23} 24 else 25 {26 textBox3.Text + = "Connection Failed \ r \ n"; 27} 28} 29 30 private void btnSendMessage_Click (object sender, EventArgs e) 31 {32 if (socket1.Connected) 33 {34 string sendMsg = textBox4.Text; 35 36 // determine whether to send 37 if (SendMsg. length <= 0) 38 {39 return; 40} 41 42 // mark 43 bool isSendSuccess = SendMsg (socket1, textBox4.Text) for successful sending ); 44 45 string recMsg = ""; 46 bool isReceiveSuccess = ReceiveMsg (socket1, ref recMsg); 47 textBox3.Text + = recMsg; 48 49 if (! (IsSendSuccess & isReceiveSuccess) 50 {51 textBox3.Text + = "the connection has been disconnected. Please reconnect "; 52} 53} 54} 55 56 // <summary> 57 // send content, and displays 58 /// </summary> 59 /// <param name = "socket"> socket of the sent content </param> 60 /// <param name = "msg "> input string </param> 61 // <returns> whether the message is sent successfully </returns> 62 private bool SendMsg (Socket socket, string msg) 63 {64 try {65 socket. send (Encoding. UTF8.GetBytes (msg); 66 return true; 67} 68 catch (Exception e) 69 {70 socket. close (); 71 return false; 72} 73} 74 75 // <summary> 76 // receives the content, and display 77 /// </summary> 78 /// <param name = "socket"> socket accepting content </param> 79 /// <param name = "msg "> output string </param> 80 // <returns> whether the message is received successfully </returns> 81 private static bool ReceiveMsg (Socket socket, ref string msg) 82 {83 try 84 {85 int recNumber; // number of received bytes 86 byte [] recBytes = new byte [1024]; // buffer byte array 87 recNumber = socket. receive (recBytes); // receiving behavior 88 byte [] recBytesForShort = new byte [recNumber]; // byteArrayForDestination 89 Array. copy (recBytes, recBytesForShort, recNumber); // Copy 90 91 // display text to construct 92 msg ++ = (Encoding. UTF8.GetString (recBytesForShort) + "\ r \ n"); 93 94 return true; 95} 96 catch (Exception e) 97 {98 socket. close (); 99 100 return false; 101} 102 103}
Client
Server:
1 static void Main (string [] args) 2 {3 // set the listening ip address and port number 4 IPAddress ip = IPAddress. parse ("192.168.120.56"); 5 IPEndPoint ipEP = new IPEndPoint (ip, 8088); 6 7 // socket 8 Socket serverSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); 9 // bind 10 serverSocket. bind (ipEP); 11 // listen to 12 serverSocket. listen (10); 13 Console. writeLine ("listener enabled \ r \ n"); 14 15 while (true) 16 {17 // This will block the current thread to wait for connection 18 Socket socketTemp = serverSocket. accept (); 19 20 // enable other threads to process data 21 ParameterizedThreadStart pts = new ParameterizedThreadStart (ReceiveAndSend); // The input method must be static 22 new Thread (pts ). start (socketTemp); 23} 24 25} 26 27 /// <summary> 28 // Method for reading and sending socket cyclically, it is recommended that multiple threads be used for asynchronous processing 29 // </summary> 30 /// <param name = "socketTemp"> single-user Socket object </param> 31 private static void ReceiveAndSend (object socketTemp) 32 {33 Socket socket = (Socket) socketTemp; 34 IPEndPoint ipep = (IPEndPoint) (socket. remoteEndPoint); 35 string ip = ipep. address. toString (); // obtain the ip address 36 string port = ipep. port. toString (); // obtain the opposite port 37 byte [] buffer = new byte [1024]; 38 39 while (true) // receive and send cyclically 40 {41 // receive and display 42 string result = ""; 43 bool isReceiveMsgSuccess = ReceiveMsg (socket, ref result); 44 if (isReceiveMsgSuccess) 45 {46 Console. writeLine (DateTime. now. toLongDateString () + "" + DateTime. now. toLongTimeString (); 47 Console. writeLine (ip + "_" + port + ":" + result); 48} 49 50 // resend 51 string sendBackStr = "received by the server:" + result; 52 SendMsg (socket, sendBackStr); 53 54 // socket. shutdown (SocketShutdown. both); 55 // socket. close (); 56 // socket. dispose (); 57} 58} 59 60 // <summary> 61 // receive the content (if it fails, the socket will be released) 62 /// </summary> 63 // <param name = "socket"> socket for content accepted </param> 64 /// <param name = "msg"> output string </param> 65 // <returns> whether received successfully </returns> 66 private static bool ReceiveMsg (Socket socket, ref string msg) 67 {68 try 69 {70 int recNumber; // number of received bytes 71 byte [] recBytes = new byte [1024]; // buffer byte array 72 recNumber = socket. receive (recBytes); // receiving behavior 73 byte [] recBytesForShort = new byte [recNumber]; 74 Array. copy (recBytes, recBytesForShort, recNumber); // Copy 75 76 // display 77 msg + = Encoding. UTF8.GetString (recBytesForShort) + "\ r \ n"; 78 79 return true; 80} 81 catch (Exception e) 82 {83 socket. close (); 84 85 return false; 86} 87 88} 89 90 // <summary> 91 // send the content (if it fails, the socket will be released) 92 /// </summary> 93 // <param name = "socket"> socket of the sent content </param> 94 /// <param name = "msg"> input string </param> 95 // <returns> whether the message is received successfully </returns> 96 private static bool SendMsg (Socket socket, string msg) 97 {98 try 99 {100 socket. send (Encoding. UTF8.GetBytes (msg); 101 return true; 102} 103 catch (Exception e) 104 {105 socket. close (); 106 return false; 107} 108}
Server
If you need source code, go to the client and server.