C# development Socket client
Let's create a new class: SocketClientAsync.
Note:
1. Since Socket communication is sent to the cache area, the data is overwritten, not new, that is, if the content we send for the first time is byte[]{0x11,0x22}; and the content we send for the second time is byte[]{0x22}. Then the data received by our server on the second time is byte[]{0x22,0x22}.
So we need to declare it in the (byte[] mes) method
byte[] buffer = new byte[1024]; for (int i = 0; i < ; i++) { buffer[i] = 0x00; }
The function is to replace all the old content every time when sending new content to the server;
2. Before closing the connection, you need to stop sending and accepting the notification server, that is,
();
Interrupt socket connection: Notify the server or client to stop receiving and sending data.
After the notification is completed, if the client is still connected, then its own connection will be disconnected.
if () { (); }
3. See the figure below for specific classes, you can use them directly
#region SocketClient Client public class SocketClientAsync { #region declare variables public string IPAdress; public bool connected = false; public Socket clientSocket; private IPEndPoint hostEndPoint; private int Flag = 0; private AutoResetEvent autoConnectEvent = new AutoResetEvent(false); private SocketAsyncEventArgs lisnterSocketAsyncEventArgs; public delegate void StartListeHandler(); public event StartListeHandler StartListen; public delegate void ReceiveMsgHandler(byte[] info, int i); public event ReceiveMsgHandler OnMsgReceived; private List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>(); #endregion #region constructor /// <summary> /// Constructor /// </summary> /// <param name="hostName"></param> /// <param name="port"></param> /// <param name="i"></param> public SocketClientAsync(string hostName, int port, int i) { Flag = i; IPAdress = hostName; IPAddress[] hostAddresses = (hostName); = new IPEndPoint(hostAddresses[ - 1], port); = new Socket(, , ); } #endregion #region Start connecting to the server /// <summary> /// Connect to the server /// </summary> /// <returns></returns> private bool Connect() { using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { = ; = ; += new EventHandler<SocketAsyncEventArgs>(); (args); bool flag = (5000); if () { = new SocketAsyncEventArgs(); byte[] buffer = new byte[1024]; = ; (buffer, 0, ); += new EventHandler<SocketAsyncEventArgs>(); (); return true; } return false; } } #endregion #region Determine whether there is a connection to the server /// <summary> /// Determine if there is a connection /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnConnect(object sender, SocketAsyncEventArgs e) { = ( == ); (); } #endregion #region Send data to the server /// <summary> /// send /// </summary> /// <param name="mes"></param> public void Send(byte[] mes) { if () { EventHandler<SocketAsyncEventArgs> handler = null; //byte[] buffer = (mes); byte[] buffer = new byte[1024]; for (int i = 0; i < ; i++) { buffer[i] = 0x00; } (mes, 0, buffer, 0, ); SocketAsyncEventArgs senderSocketAsyncEventArgs = null; lock (s_lst) { if (s_lst.Count > 0) { senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1]; s_lst.RemoveAt(s_lst.Count - 1); } } if (senderSocketAsyncEventArgs == null) { senderSocketAsyncEventArgs = new SocketAsyncEventArgs(); = ; = ; if (handler == null) { handler = delegate(object sender, SocketAsyncEventArgs _e) { lock (s_lst) { s_lst.Add(senderSocketAsyncEventArgs); } }; } += handler; } (buffer, 0, ); (senderSocketAsyncEventArgs); } else { = false; } } #endregion #region Listening Server /// <summary> /// Listen to the server /// </summary> public void Listen() { if ( && != null) { try { ( as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs); } catch (Exception) { } } } #endregion #region Disconnect the server /// <summary> /// Disconnect /// </summary> /// <returns></returns> private int Disconnect() { int res = 0; try { (); } catch (Exception) { } try { (); } catch (Exception) { } = false; return res; } #endregion #region Data Receive /// <summary> /// Data Acceptance /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnReceive(object sender, SocketAsyncEventArgs e) { if ( == 0) { if () { try { (); } catch (Exception) { } finally { if () { (); } } } byte[] info = new Byte[] { 0 }; (info, Flag); } else { byte[] buffer = new byte[]; (, 0, buffer, 0, ); (buffer, Flag); Listen(); } } #endregion #region Method to establish a connection to the server /// <summary> /// Method to establish a connection /// </summary> /// <returns></returns> public bool ConnectServer() { bool flag = false; += new StartListeHandler(SocketClient_StartListen); // += new ReceiveMsgHandler(SocketClient_OnMsgReceived); flag = (); if (!flag) { return flag; } return true; } #endregion #region Close connection with the server /// <summary> /// Method to close the connection /// </summary> /// <returns></returns> public int CloseLinkServer() { return (); } #endregion #region listening method /// <summary> /// How to listen /// </summary> private void SocketClient_StartListen() { (); } #endregion #region IDispose member public void Dispose() { if () { (); } } #endregion #region destructor ~SocketClientAsync() { try { if () { (); } } catch { } finally { } } #endregion } #endregion
4. Then the class call
//Declare the definition variable private SocketClientAsync ClientLink;//Client connection object private string Client_IP = "127.0.0.1";//Server IP address private int Client_Port = 12345;//The port number of the server listening private Thread Client_Td;//Internal communication thread private bool ClientLinkRes = false;//Server communication status flag private bool ThreadContinue = true;//Thread polling flag private bool isOnline = false;//Is it online sign /// <summary> /// Start the thread /// </summary> private void StartServer() { Client_Td = new Thread(LinkSocketSerFunc); Client_Td.Start(); } /// <summary> /// Reconnect the server thread /// </summary> private void LinkSocketSerFunc() { object lockobj = new object(); int heartBeatCount = 0; ClientLink = new SocketClientAsync(Client_IP, Client_Port, 0); bool NotFirstIn = false; while (ThreadContinue) { try { if (!ClientLinkRes) { isOnline = false; if (NotFirstIn) { (); ClientLink = new SocketClientAsync(Client_IP, Client_Port, 0); } NotFirstIn = true; += new (Client_OnMsgReceived);//Bind an event that receives server messages ClientLinkRes = (); } else { //The logical processing of successful communication is written here } } catch (Exception ex) { ClientLinkRes = false; (()); } (1000); } } /// <summary> /// Receive message processing /// </summary> /// <param name="info"></param> /// <param name="num"></param> private void Client_OnMsgReceived(byte[] info, int num) { try { ClientHeartBeat = 0; if ( > 0 && info[0] != 0)//BCR connection error NO { //Info is required to receive the byte array sent from the server, what kind of logical processing is needed to be written here } else { ClientLinkRes = false; } } catch (Exception ex) { (()); } } /// <summary> /// Terminate the service /// </summary> public void StopServer() { if (ClientLinkRes) { ThreadContinue = false; (); (); } }
This basic Socket client backend is finished and can be copied and used directly. Usually, I write Socket client like this. After sharing it, everyone can use it directly!
Asynchronous implementation of C# Socket client
Simple packaging
using System; using ; using ; using ; using ; using ; using ; namespace dclient { public delegate void DelegateMsg(object msg); public class Client { private static Socket _clientSocket; private static string _server; private static int _port; public static DelegateMsg OnConnect; public static DelegateMsg OnSend; public static DelegateMsg OnReceive; public static DelegateMsg OnServerDown; public static DelegateMsg OnErr; public static void Connect() { try { _server = ["serverIp"]; _port = (["serverPort"]); IPEndPoint ip = new IPEndPoint((_server), _port); _clientSocket = new Socket(, , ); _clientSocket.BeginConnect(ip, new AsyncCallback(ConnectCallBack), _clientSocket); } catch (Exception e) { throw e; } } private static void ConnectCallBack(IAsyncResult iar) { Socket client = (Socket); try { (iar); OnConnect("Connected"); } catch (SocketException e) { if ( == 10061) { OnErr("The server program is not running or the server port is not open"); } else { OnErr(); } } finally { } } public static void Send(string msg) { if (_clientSocket == null || msg == ) return; msg += "\r\n"; byte[] data = Encoding.(msg); try { _clientSocket.BeginSend(data, 0, , , asyncResult => { int length = _clientSocket.EndSend(asyncResult); OnSend(("Client sends messages:{0}", msg)); }, null); } catch (Exception e) { OnErr(); } } public static void Recive() { byte[] data = new byte[1024]; try { _clientSocket.BeginReceive(data, 0, , , asyncResult => { try { int length = _clientSocket.EndReceive(asyncResult); OnReceive(("Received a server message:length:{1},{0}", Encoding.(data), length)); Recive(); } catch (SocketException e) { if ( == 10054) { OnServerDown("The server is disconnected"); } else { OnErr(); } } }, null); } catch (Exception ex) { OnErr(); } } } }
use
public partial class Form1 : Form { public Form1() { InitializeComponent(); += new DelegateMsg(connect); += new DelegateMsg(send); += new DelegateMsg(receive); += new DelegateMsg(svrdown); += new DelegateMsg(onerr); } private void Form1_Load(object sender, EventArgs e) { (); } private void connect(object msg) { (()); ("DALO Send Test"); (); } private void send(object msg) { (()); } private void receive(object msg) { (()); } private void svrdown(object msg) { (()); } private void onerr(object msg) { (()); } }
Several common operations not implemented
1. Receive the package of large amounts of data sent by the server.
2. After the server is disconnected, the client will automatically detect and reconnect. You must first release the _clientSocket.
3. Heartbeat bag.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.