Let me first talk about my understanding of the entire Socket communication process. After all, I am a beginner, I forgive you for saying something wrong, and I will correct it if I know I am wrong~
First, create a new serverSocket on the server side and initialize it (generally include AddressFamily: IP address type, SocketType:Socket data transmission method, ProtoType: Transfer protocol);
Next we need to set the IP:port to bind to the server side; and then start listening and set up at most how many clients to listen to at the same time.
At this time, the server is waiting until a client connects to this ip:port. At this time, () works and obtains this connection. (The connection at this time has address information! Remember to save)
After obtaining the connection, the server can communicate with this Client. When adding the second Client (we call it ClientB), the Server receives the ClientB message and can forward the message to the previous Client (we call it ClientA). When receiving the ClientA message, it can also forward it to ClientB. This enables communication between clients. (The focus is on saving connection information!!)
Then now post the code to explain:
Server side code
namespace SocketServer { class Program { private static byte[] result = new byte[1024]; static Socket serverSocket; private static string client; private static Socket clientSocket; //I have saved two clients here, because I have opened two clients on my computer, so there will be no more. //In theory, a Socket[] should be opened to save information. It is best to use a binary to bind the client's information and connection. //This way, you can realize that the next login will be identified as this Client after disconnecting. private static Socket clientSocketA=null; private static Socket clientSocketB=null; static void Main(string[] args) { (8885); } private static void SetPort(int port) { IPAddress ip = ("127.0.0.1");//set ip serverSocket = new Socket(, , );//initialize (new IPEndPoint(ip, port));//bind (10); //Enter the listening state ("monitor{0}success", ()); //Open a thread to listen to client connection Thread myThread = new Thread(ListenClientConnect); (); (); } /// <summary> /// Listen to client connections /// </summary> private static void ListenClientConnect() { while (true) { //After connecting to the Client, get this connection clientSocket = (); //I only have two clients here, so I just wrote it simply if (clientSocketA == null) { clientSocketA = clientSocket; } else if (clientSocketB == null) { clientSocketB = clientSocket; } else { //When one of them is disconnected and reconnected, you need to save the connection again if () { clientSocketA = clientSocketB; clientSocketB = clientSocket; } else { clientSocketB = clientSocketA; clientSocketA = clientSocket; } } (("say hello")); //Open a thread to receive Client information Thread receivedThread = new Thread(ReceiveMessage); (clientSocket); } } private static void ReceiveMessage(object clientSocket) { Socket myClientSocket = (Socket) clientSocket; while (true) { try { int revceiveNumber = (result); //("Accept client {0} message{1}", () // , (result, 0, revceiveNumber)); ((result, 0, revceiveNumber)); if (myClientSocket == clientSocketA) { ("receive from A"); if (clientSocketB!=null&&) { ("a IS BOUND"); (result, 0, revceiveNumber, ); } else { (("the people is not online! Send Failed!")); ("If the other party is not online, the sending failed!"); } } else { ("receive from B"); if (clientSocketA != null && ) { ("a IS BOUND"); (result, 0, revceiveNumber, ); } else { (("the people is not online! Send Failed!")); ("If the other party is not online, the sending failed!"); } } } catch(Exception ex) { (); (); (); break; } } } } }
Client side code (because they are almost the same, just post one)
namespace SocketClient { class Program { private static byte[] result = new byte[1024]; private static Socket clientSocket; private static void ListenServer() { while (true) { result = new byte[1024]; int receiveLength = (result); ("{0}", (result, 0, receiveLength)); } } static void Main(string[] args) { IPAddress ip = ("127.0.0.1"); clientSocket = new Socket(, , ); try { (ip, 8885); ("The connection was successful!"); } catch (Exception e) { ("Connection failed!"); return; } Thread threadRead = new Thread(ListenServer); (); while(true) { try { (1000); string sendMessage = (); (("Sylvia:"+sendMessage)); } catch (Exception ex) { (); (); break; } } ("Send Completed Press Enter to exit"); (); } } }
When writing, pay special attention to the Send information and pay attention to the transmission size of byte[]. It is easy to become the size of the byte[] array instead of the content size.
Let's try this for yourself.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.