How to use Socket to realize the communication between server and multiple clients in C #
This article mainly introduces how C # uses Socket to achieve server communication with multiple clients. It is very detailed and has certain reference value. Interested friends must finish reading it.
Extension: since the server side stores all the connection objects between server and client, we can implement a chat system based on this demo:
* whenever a user speaks to a user, the message of a user is received by server, and the server can send the information sent by that user to each connected user (excluding the sender) through a loop.
Server side code:
Class Program {/ / create a socket static Socket SocketWatch = null; / / that communicates with the client, defining a collection that stores client information static Dictionary ClientConnectionItems = new Dictionary {}; static void Main (string [] args) {/ / port number (for listening) int port = 6000; / / string host = "127.0.0.1"; / / IPAddress ip = IPAddress.Parse (host); IPAddress ip = IPAddress.Any / bind the IP address and port number to the network node point IPEndPoint ipe = new IPEndPoint (ip, port); / / define a socket to listen for messages sent by the client, including three parameters (IP4 addressing protocol, streaming connection, Tcp protocol) SocketWatch = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / listen on the bound network node SocketWatch.Bind (ipe) / / limit the listening queue length of the socket to 20 SocketWatch.Listen (20); / / the thread responsible for listening on the client: create a listening thread Thread threadwatch = new Thread (WatchConnecting); / / set the form thread to synchronize with the background, and end threadwatch.IsBackground = true; / / start thread threadwatch.Start () with the end of the main thread Console.WriteLine ("enable listening."); Console.WriteLine ("Click enter any data to exit the program."); Console.ReadKey (); SocketWatch.Close (); / / Socket serverSocket = null; / / int item1; / / while (true) / / {/ receive message / / serverSocket = SocketWatch.Accept () / / Console.WriteLine ("connection established!") / / string recStr = ""; / / byte [] recByte = new byte [4096]; / / int bytes = serverSocket.Receive (recByte, recByte.Length, 0); / recStr + = Encoding.ASCII.GetString (recByte, 0, bytes); / / recStr + = Encoding.GetEncoding ("utf-8") .GetString (recByte, 0, bytes); / send message / / Console.WriteLine (recStr) / / Console.Write ("Please enter:"); / / string sendStr = Console.ReadLine (); / byte [] sendByte = Encoding.ASCII.GetBytes (sendStr); / / byte [] sendByte = Encoding.GetEncoding ("utf-8") .GetBytes (sendStr); / Thread.Sleep (4000); / / serverSocket.Send (sendByte, sendByte.Length, 0); / / serverSocket.Close () / / if (I > = 100) / / {/ / break; /} / / iTunes; / /} / / sSocket.Close (); / / Console.WriteLine ("connection closed!") ; / / Console.ReadLine ();} / / listen for requests from the client static void WatchConnecting () {Socket connection = null; / / continuously listen for requests from the client while (true) {try {connection = SocketWatch.Accept () } catch (Exception ex) {/ / prompt socket listening exception Console.WriteLine (ex.Message); break;} / / client network node number string remoteEndPoint = connection.RemoteEndPoint.ToString (); / / add client information ClientConnectionItems.Add (remoteEndPoint, connection) / / displays the connection with the client Console.WriteLine ("\ r\ n [client\"+ remoteEndPoint +"\ "established successfully! Number of clients: "+ ClientConnectionItems .count +"]); / / get the client's IP and port number IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint) .Address; int clientPort = (connection.RemoteEndPoint as IPEndPoint) .Port; / / Let the customer display the message "connected successfully" string sendmsg = "[" + "Local IP:" + clientIP + "Local Port:" + clientPort.ToString () + "connection to the server is successful!]" ; byte [] arrSendMsg = Encoding.UTF8.GetBytes (sendmsg); connection.Send (arrSendMsg); / / create a communication thread Thread thread = new Thread (recv); / / set to background thread, exit thread.IsBackground = true; / / start thread thread.Start (connection) as the main thread exits } / receive a message from the client, client socket object / static void recv (object socketclientpara) {Socket socketServer = socketclientpara as Socket; while (true) {/ / create a memory buffer with a size of 1024 byte 1024 bytes, that is, 1m byte [] arrServerRecMsg = new byte [1024 socket 1024] / / stores the received information in the memory buffer and returns the length of its byte array try {int length = socketServer.Receive (arrServerRecMsg); / / converts the byte array received by the machine into a human-readable string string strSRecMsg = Encoding.UTF8.GetString (arrServerRecMsg, 0, length) / / append the sent string information to the text box txtMsg Console.WriteLine ("\ r\ n [client:" + socketServer.RemoteEndPoint + "time:" + DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss:fff") + "]\ r\ n" + strSRecMsg); / / Thread.Sleep (3000) / / socketServer.Send (Encoding.UTF8.GetBytes ("[" + socketServer.RemoteEndPoint + "]:" + strSRecMsg)); / / send client data if (ClientConnectionItems.Count > 0) {foreach (var socketTemp in ClientConnectionItems) {socketTemp.Value.Send (Encoding.UTF8.GetBytes ("[" + socketServer.RemoteEndPoint + "]:" + strSRecMsg) } catch (Exception) {ClientConnectionItems.Remove (socketServer.RemoteEndPoint.ToString ()); / / prompt socket snooping exception Console.WriteLine ("\ r\ n [client\"+ socketServer.RemoteEndPoint +"\ "has been disconnected! Number of clients: "+ ClientConnectionItems.Count+"] "); / / close the socket socketServer.Close (), which is used by accept to communicate with the client; break;}
Client side code:
Class Program {/ / create a client socket and a thread responsible for listening to server requests static Thread ThreadClient = null; static Socket SocketClient = null; static void Main (string [] args) {try {int port = 6000; string host = "127.0.0.1"; / / server-side ip address IPAddress ip = IPAddress.Parse (host); IPEndPoint ipe = new IPEndPoint (ip, port) / / define a socket listener SocketClient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try {/ / client socket connects to the network node using Connect SocketClient.Connect (ipe);} catch (Exception) {Console.WriteLine ("connection failed! \ r\ n "); Console.ReadLine (); return;} ThreadClient = new Thread (Recv); ThreadClient.IsBackground = true; ThreadClient.Start (); Thread.Sleep (1000); Console.WriteLine (" Please enter content:\ r\ n "); while (true) {string sendStr = Console.ReadLine (); ClientSendMsg (sendStr) } / / int I = 1; / / while (true) / / {/ / Console.Write ("Please enter content:"); / / string sendStr = Console.ReadLine (); / / Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / clientSocket.Connect (ipe) / send message / byte [] sendBytes = Encoding.ASCII.GetBytes (sendStr); / / byte [] sendBytes = Encoding.GetEncoding ("utf-8") .GetBytes (sendStr); / Thread.Sleep (4000); / / clientSocket.Send (sendBytes); / receive message / / string recStr = ""; / / byte [] recBytes = new byte [4096] / / int bytes = clientSocket.Receive (recBytes, recBytes.Length, 0); / recStr + = Encoding.ASCII.GetString (recBytes, 0, bytes); / / recStr + = Encoding.GetEncoding ("utf-8") .GetString (recBytes, 0, bytes); / / Console.WriteLine (recStr); / / clientSocket.Close (); / / if (I > = 100) / / {/ / break / / return; / / Console.ReadLine (); / / return; / / string result = String.Empty;} catch (Exception ex) {Console.WriteLine (ex.Message); Console.ReadLine ();}} / / the method public static void Recv () {int x = 0 to receive a message from the server / / continuously listen for messages sent by the server while (true) {try {/ / define a 1m memory buffer for temporarily storing received messages byte [] arrRecvmsg = new byte [1024 * 1024]; / / store the data received by the client socket in the memory buffer and get the int length = SocketClient.Receive (arrRecvmsg) / / convert the character array obtained by the socket into a human-readable string string strRevMsg = Encoding.UTF8.GetString (arrRecvmsg, 0, length); if (x = = 1) {Console.WriteLine ("\ r\ nServer:" + DateTime.Now.ToString ("yyyy-MM-dd HH:mm:ss:fff") + "\ r\ n" + strRevMsg+ "\ r\ n") } else {Console.WriteLine (strRevMsg + "\ r\ n"); x = 1;}} catch (Exception ex) {Console.WriteLine ("the remote server has been disconnected!" + ex.Message + "\ r\ n"); break;} / / method of sending character information to the server public static void ClientSendMsg (string sendMsg) {/ / convert the input content string into a machine-recognizable byte array byte [] arrClientSendMsg = Encoding.UTF8.GetBytes (sendMsg); / / call the client socket to send the byte array SocketClient.Send (arrClientSendMsg) }} these are all the contents of the article "how to use Socket to implement server communication with multiple clients in C #". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!