. Net Socket communication can use Socket classes, or TcpClient, TcpListener, and UdpClient classes. I am using the Socket class, Tcp protocol.
The program is very simple. It is a command line server and a command line client. After the server starts, it binds the local port based on the input port number and starts listening. After the client starts, it connects to the server based on the number of clients, service IP addresses, and service port number entered. After the client connection is successful, start a new thread to randomly send messages to the server and wait for receiving the messages returned by the server. After the server and the client have successfully created a connection, start the new thread to receive messages from the client and return a message from the client, this loop goes on ......
:
Key server code
Start listening:
endPoint = IPEndPoint( socket = socket.Listen(.MaxValue);
Start a new thread to receive client connections:
socketThread = Thread(OnSocketAccept) {IsBackground = Show();
Receive client connection details:
OnSocketAccept( socket = obj ( Socket clientSocket = (! ClientDict[key] = }
Send/receive data:
OnSendOrReceive( socket = obj ( receiveLength = sendLength = }
Close connection:
socket.Disconnect( }
Key client code
Connect to the server:
( i = ; i <= clientNum; i++ ConnetServer(IPAddress address, port, clientSocket =
The same code is used for sending/receiving data and disabling connection.
The thread pool thread is used first, and the Server accepts the client connection to use an independent thread (socketThread). This thread may need to be stopped manually.
Use Monitor. TryEnter (ClientDictLock, LockTimeOut) and Monitor. Exit (ClientDictLock). Consider that the lock may form a deadlock and use the lock.
I am a beginner. Thank you for your criticism!
Source code download