C # Use the server to implement communication between clients,

Source: Internet
Author: User

C # Use the server to implement communication between clients,

These two days I have been studying C #, C # advanced programming is really a thick book QAQ.

Yesterday I read the Communication Section (but I haven't read it yet), read the blogs of some people on the Internet, and wrote a communication based on their blogs.

First, let me explain my understanding of the entire Socket communication process. After all, I am a beginner and sorry for the mistake. If I know it, I will correct it ~

First, create a new serverSocket on the server and initialize it (generally including AddressFamily: IP Address type, SocketType: Socket data transmission mode, ProtoType: Transmission Protocol );

Next we need to set the IP: port to be bound to the server, then start listening, and set the maximum number of clients to be monitored at the same time.

 

At this time, the server is waiting until a Client connects to this ip: port, then serverSocket. Accept () works to obtain this connection. (The connection has the address information! Remember to save)

After the connection is obtained, the server can communicate with the Client. When the second Client (called ClientB) is added, the Server receives the message from ClientB, this message can be forwarded to the previous Client (we call it ClientA). When a message is received by ClientA, it can also be forwarded to ClientB. In this way, the communication between Clients is realized. (Focus on saving connection information !!)

 

Now, the following code is added:

Server code

1 namespace SocketServer 2 {3 class Program 4 {5 private static byte [] result = new byte [1024]; 6 7 static Socket serverSocket; 8 private static string client; 9 private static Socket clientSocket; 10 // I have saved two clients here, because I have opened two clients on my computer, there will be no more 11 // theoretically a Socket [] should be opened to save the information, it is best to bind the client information and connection with a Binary Group 12 // so that the next login after the connection is disconnected can still identify whether the Client 13 private static Socket clientSocketA = null; 14 private static Socket ClientSocketB = null; 15 16 static void Main (string [] args) 17 {18 Program. setPort (8885); 19} 20 private static void SetPort (int port) 21 {22 IPAddress ip = IPAddress. parse ("127.0.0.1"); // set ip 23 serverSocket = new Socket (AddressFamily. interNetwork, 24 SocketType. stream, ProtocolType. tcp); // initialize 25 serverSocket. bind (new IPEndPoint (ip, port); // bind 26 serverSocket. listen (10); 27 // enter the listening status 28 Console. writeLine ("listener {0} succeeded", serverSocket. localEndPoint. toString (); 29 // start a Thread to listen to the client connection 30 Thread myThread = new Thread (ListenClientConnect); 31 myThread. start (); 32 Console. readLine (); 33 34} 35 // <summary> 36 // listen for client connection 37 /// </summary> 38 private static void ListenClientConnect () 39 {40 while (true) 41 {42 // obtain the connection 43 clientSocket = serverSocket after the Client is connected. accept (); 44 45 // here I only have two Therefore, we simply wrote 46 if (clientSocketA = null) 47 {48 clientSocketA = clientSocket; 49} 50 else if (clientSocketB = null) 51 {52 clientSocketB = clientSocket; 53} 54 else 55 {56 // when one of them is disconnected and reconnects, you need to save the connection 57 if (clientSocketB. isBound) 58 {59 clientSocketA = clientSocketB; 60 clientSocketB = clientSocket; 61} 62 else 63 {64 clientSocketB = clientSocketA; 65 clientSocketA = clientSocket; 66} 67 68} 69 clientSocket. send (Encoding. ASCII. getBytes ("say hello"); 70 // open a Thread to receive Client information 71 Thread receivedThread = new Thread (ReceiveMessage); 72 receivedThread. start (clientSocket); 73 74} 75} 76 77 private static void ReceiveMessage (object clientSocket) 78 {79 Socket myClientSocket = (Socket) clientSocket; 80 81 while (true) 82 {83 try 84 {85 int revceiveNumber = myClientSocket. receive (res Ult); 86 // Console. writeLine ("accept client {0} message {1}", myClientSocket. remoteEndPoint. toString () 87 //, Encoding. ASCII. getString (result, 0, revceiveNumber); 88 Console. writeLine (Encoding. ASCII. getString (result, 0, revceiveNumber); 89 if (myClientSocket = clientSocketA) 90 {91 Console. writeLine ("receive from A"); 92 if (clientSocketB! = Null & clientSocketB. isBound) 93 {94 Console. writeLine ("a is bound"); 95 clientSocketB. send (result, 0, revceiveNumber, SocketFlags. none); 96} 97 else 98 {99 myClientSocket. send (Encoding. ASCII. getBytes ("the people is not online! Send Failed! "); 100 Console. WriteLine (" the recipient is not online. failed to send! "); 101} 102} 103 else104 {105 Console. WriteLine (" receive from B "); 106 if (clientSocketA! = Null & clientSocketA. isBound) 107 {108 Console. writeLine ("a is bound"); 109 clientSocketA. send (result, 0, revceiveNumber, SocketFlags. none); 110} 111 else112 {113 myClientSocket. send (Encoding. ASCII. getBytes ("the people is not online! Send Failed! "); 114 Console. WriteLine (" the recipient is not online. failed to send! "); 115} 116 117} 118 119} 120 catch (Exception ex) 121 {122 Console. writeLine (ex. message); 123 myClientSocket. shutdown (SocketShutdown. both); 124 myClientSocket. close (); 125 break; 126 127} 128} 129 130} 131} 132}

Client code(Because it is almost the same)

1 namespace SocketClient 2 {3 class Program 4 {5 private static byte [] result = new byte [1024]; 6 private static Socket clientSocket; 7 private static void ListenServer () 8 {9 while (true) 10 {11 result = new byte [1024]; 12 int pair elength = clientSocket. receive (result); 13 14 Console. writeLine ("{0}", Encoding. ASCII. getString (result, 0, cancelength); 15} 16 17} 18 static void Main (string [] args) 19 {20 21 IPAddress ip = IPAddress. parse ("127.0.0.1"); 22 clientSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); 23 try24 {25 clientSocket. connect (ip, 8885); 26 Console. writeLine ("connection successful! "); 27 28} 29 catch (Exception e) 30 {31 Console. WriteLine (" connection failed! "); 32 return; 33} 34 Thread threadRead = new Thread (ListenServer); 35 threadRead. start (); 36 37 38 while (true) 39 {40 try41 {42 Thread. sleep (1000); 43 string sendMessage = Console. readLine (); 44 clientSocket. send (Encoding. ASCII. getBytes ("Sylvia:" + sendMessage); 45 46} 47 catch (Exception ex) 48 {49 clientSocket. shutdown (SocketShutdown. both); 50 clientSocket. close (); 51 break; 52} 53 54} 55 Console. writeLine ("after sending, press enter to exit"); 56 Console. readKey (); 57} 58} 59}

 

When writing data, pay special attention to the transmission size of the byte [], which is easily changed to the size of the byte [] array instead of the content.

Let's try it by yourself.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.