C# winfroms uses socket client server code to explain in detail, declaring Socket the first parameter: addressing method, the second parameter: data transmission method, the third parameter: communication protocol Socket socket = new Socket(,,); Turn on listening Parameters refer to the number of clients that can be connected (10); (); It should be noted here that Accept() will block the thread until the client is connected. If placed in the main thread, the foreground operation will be blocked. A new thread needs to be created. Accept() returns a socket. After the client connects, the server automatically generates a socket and the connection client communication. After the connection is successful, send "Connection is successful!" to the client.
1. Communication related instructions
1.1 Server and Client
After starting the server, the server continuously listens to requests sent by the client. Once the information (request) is heard from the client, the two ends can send messages to each other.
The server needs to bind an IP to be used by the client to find and establish a connection in the network (supports mutual communication between the client and the server within the LAN)
1.2 Information sending principle
Convert the manually input string information into a byte array that the machine can recognize, and then call the socket's Send() method to send the byte array out.
1.3 Information Receiving Principle
Call the socket's Receive() method, get the byte array passed by the peer, and then convert it into string information that people can understand
Code
2.1 Client Code
using System; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; namespace TcpMsgClient { public partial class FrmClient : Form { public FrmClient() { InitializeComponent(); //Close the illegal thread operation check for text box = false; } //Create 1 client socket and 1 thread responsible for listening to server requests Socket socketClient = null; Thread threadClient = null; /// <summary> /// Connect to server event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnListenServer_Click(object sender, EventArgs e) { //Define a set of byte listening, including 3 parameters (IP4 addressing protocol, streaming connection, TCP protocol) socketClient = new Socket(, , ); // Need to get the IP address in the text box IPAddress ipaddress = (()); //Bind the obtained ip address and port number to the network node endpoint IPEndPoint endpoint = new IPEndPoint(ipaddress, (())); //The method used to connect the client socket to the network node (server) is Connect instead of Bind try { (endpoint); ("The client connects to the server successfully!" + "\r\n"); = false; //Create a thread to listen to messages sent by the server threadClient = new Thread(RecMsg); //Set the form thread to synchronize with the background = true; //Start the thread (); } catch (Exception ex) { ("The remote server disconnects, connection failed!" + "\r\n"); } } /// <summary> /// Method of receiving information sent by the server /// </summary> private void RecMsg() { while (true) //Continue to listen to messages sent from the server { try { //Define a 1M memory buffer for temporarily storing received information byte[] arrRecMsg = new byte[1024 * 1024]; //Save the data received by the client socket into the memory buffer and obtain its length int length = (arrRecMsg); //Convert the byte array obtained by the socket into a string that people can understand string strRecMsg = Encoding.(arrRecMsg, 0, length); //Add the sent information to the chat content text box ("Server side" + GetCurrentTime() + "\r\n" + strRecMsg + "\r\n"); } catch (Exception ex) { ("The remote server has been disconnected!"+"\r\n"); = true; break; } } } /// <summary> /// Method to send string information to the server /// </summary> /// <param name="sendMsg">Send string information</param> private void ClientSendMsg(string sendMsg) { try { //Convert the input content string into a byte array that the machine can recognize byte[] arrClientSendMsg = Encoding.(sendMsg); //Calling client socket to send byte array (arrClientSendMsg); //Add the sent information to the chat content text box ("Everyone" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n"); } catch(Exception ex){ ("The remote server has been disconnected and cannot send messages!" + "\r\n"); } } private void btnSendMsg_Click(object sender, EventArgs e) { //Calling ClientSendMsg method to send the information entered in the text box to the server ClientSendMsg(()); (); } private void txtClientSendMsg_KeyDown(object sender, KeyEventArgs e) { //When the cursor is in the text box If the user presses the Enter key on the keyboard if ( == ) { //Then call the method of sending information to the server ClientSendMsg(()); (); } } /// <summary> /// Method to get the current system time /// </summary> /// <returns>Current time</returns> private DateTime GetCurrentTime() { DateTime currentTime = new DateTime(); currentTime = ; return currentTime; } } }
2.2 Server code
using System; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; namespace TcpMsgServer { public partial class FrmServer : Form { public FrmServer() { InitializeComponent(); //Close the illegal thread operation check for text box = false; } Thread threadWatch = null; //Responsible for listening to the client's thread Socket socketWatch = null; //Responsible for listening to the client's socket /// <summary> /// Start the service /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnServerConn_Click(object sender, EventArgs e) { try { //Define a socket to listen to information sent by the client. It contains 3 parameters (IP4 addressing protocol, streaming connection, TCP protocol) socketWatch = new Socket(, , ); //The server needs to send information 1 IP address and port number IPAddress ipaddress = (()); //Get the IP address entered in the text box //Bind the IP address and port number to the endpoint of the network node IPEndPoint endpoint = new IPEndPoint(ipaddress, (())); //Get the port number entered in the text box // Listen to the bound network node (endpoint); //Limit the socket's listening queue length to 20 (20); //Create a listener thread threadWatch = new Thread(WatchConnecting); //Set the form thread to synchronize with the background = true; //Start the thread (); //After starting the thread, the txtMsg text box displays the corresponding prompt. ("Start listen to messages from the client!" + "\r\n"); = false; } catch (Exception ex) { ("The server failed to start the service!" + "\r\n"); = true; } } //Create a socket responsible for communicating with the client Socket socConnection = null; /// <summary> /// Listen to requests sent by the client /// </summary> private void WatchConnecting() { while (true) //Continuously listen to requests sent by the client { socConnection = (); ("The client connection was successful!" + "\r\n"); //Create a communication thread ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg); Thread thr = new Thread(pts); = true; //Start the thread (socConnection); } } /// <summary> /// Method to send information to the client /// </summary> /// <param name="sendMsg">Send string information</param> private void ServerSendMsg(string sendMsg) { try { //Convert the input string into a byte array that the machine can recognize byte[] arrSendMsg = Encoding.(sendMsg); //Send byte array information to the client (arrSendMsg); //Add the sent string information to the text box txtMsg ("server " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n"); } catch (Exception ex) { ("The client has been disconnected and cannot send messages!" + "\r\n"); } } /// <summary> /// Receive messages sent by the client /// </summary> /// <param name="socketClientPara">Client socket object</param> private void ServerRecMsg(object socketClientPara) { Socket socketServer = socketClientPara as Socket; while (true) { //Create a memory buffer with a size of 1024*1024 bytes, i.e. 1M byte[] arrServerRecMsg = new byte[1024 * 1024]; try { //Save the received information into the memory buffer and return the length of its byte array int length = (arrServerRecMsg); //Convert the byte array received by the machine into a string that can be understood by humans string strSRecMsg = Encoding.(arrServerRecMsg, 0, length); //Add the sent string information to the text box txtMsg ("Everyone" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n"); } catch (Exception ex) { ("The client has been disconnected!" + "\r\n"); break; } } } /// <summary> /// Send a message to the client /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSendMsg_Click(object sender, EventArgs e) { //Call ServerSendMsg method to send information to the client ServerSendMsg(()); (); } /// <summary> /// Shortcut key Enter Send message /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtSendMsg_KeyDown(object sender, KeyEventArgs e) { //If the user presses the Enter key if ( == ) { //Then call the method of the server sending information to the client ServerSendMsg(()); (); } } /// <summary> /// Method to get the current system time /// </summary> /// <returns>Current time</returns> private DateTime GetCurrentTime() { DateTime currentTime = new DateTime(); currentTime = ; return currentTime; } /// <summary> /// Get the local IPv4 address /// </summary> /// <returns></returns> public IPAddress GetLocalIPv4Address() { IPAddress localIpv4 = null; //Get the list of all IP addresses of the machine IPAddress[] IpList = (()); //Loop through all IP addresses foreach (IPAddress IP in IpList) { //Discern whether it is an IPv4 address if ( == ) { localIpv4 = IP; } else { continue; } } return localIpv4; } /// <summary> /// Get local IP events /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGetLocalIP_Click(object sender, EventArgs e) { //The address of the IPv4 is received IPAddress localIP = GetLocalIPv4Address(); // Assign to the text box = (); } } }
3. Timed task processing messages
Timers timing tasks
In the case of internal multithreading, this timing task supports, starts, sets conditions, and executes the task after it is met. If it is not satisfied, it will be executed and then automatically destroyed.
using ; using ; using ; using System; using ; using ; using ; using ; using ; using ; namespace { public class MsgReply { private ServiceMain _serviceMain; private readonly _timer; public static string clicentInfo_value = ""; // Device information [IP: Port] public static string mainName_value=""; //Form name public static string msgContent= MsgUtils.MSG_QDLL;//Message content public int msgNum=0;//Resent times up to three times public MsgReply(string msgValue,string clientInfo,string mainName, ServiceMain serviceMain) { clicentInfo_value = clientInfo; mainName_value = mainName; _serviceMain = serviceMain; msgContent = msgValue; // Set timer interval (units in milliseconds) _timer = new (5000); // Add Elapsed event handler _timer.Elapsed += OnTimerElapsed; // Start timer _timer.Start(); } protected virtual void OnTimerElapsed(object sender, ElapsedEventArgs e) { ("The timing task triggered no reply message received!", "Message Receive Timing Task"); } public void Dispose() { (clicentInfo_value + "Timed task is closed!", "Message Receive Timing Task"); if (_timer != null && _timer.Enabled) _timer.Stop(); _timer?.Dispose(); } } }
This is the article about the sample code of C# winfroms using socket client server. For more related content on C# socket client server, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!