Client code
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Data;
Using System. Net;
Using System. Threading;
Using System. Net. Sockets;
Namespace W. Common
{
Public class CacheSocket
{
Public Socket skClient;
Public string ip = string. Empty;
Public int port =-1;
Public int netID;
// Public int timeSleep = 1;
// Receiving and sending temporary information each time
Private byte [] sendData; // message sent
Private byte [] receiveData = new byte [1024]; // receive information
Private int receiveN;
Private bool isErr = false;
//--------
Public CacheSocket (int pNetID)
{
This. netID = pNetID;
GetConfig ();
Connection ();
Cmd ("netid:" + this. netID );
}
Public CacheSocket (int pNetID, string pIP, int pPort)
{
This. ip = pIP;
This. port = pPort;
Connection ();
Cmd ("netid:" + pNetID );
}
Public string Cmd (string key)
{
Lock (this) // the process of sending a message and receiving it again.
{
This. sendData = Encoding. UTF8.GetBytes (key );
Try
{
This. skClient. Send (this. sendData );
}
Catch (Exception ex)
{
IsErr = true;
("Send" + ex. Message). WriteLine ();
ReSocket () =>{ this. skClient. Send (this. sendData );});
}
Try
{
This. incluen = this. skClient. Receive (this. receiveData );
}
Catch (Exception ex)
{
IsErr = true;
ReSocket () => {this. Allowed en = this. skClient. Receive (this. receiveData );});
("Receive" + ex. Message). WriteLine ();
}
Return Encoding. UTF8.GetString (this. receiveData, 0, this. En en );
}
}
Public delegate void ReSocket_D ();
Private void ReSocket (ReSocket_D)
{
If (isErr)
{
Connection ();
This. sendData = Encoding. UTF8.GetBytes ("netid:" + this. netID );
This. skClient. Send (this. sendData );
This. incluen = this. skClient. Receive (this. receiveData );
If (Encoding. UTF8.GetString (this. receiveData, 0, this. En en )! = "1 ")
{
}
D ();
This. isErr = false;
}
}
# Region obtain IP addresses and ports
Private void GetConfig ()
{
This. ip = "127.0.0.1 ";
This. port = 1234;
}
# Endregion
# Region connection socket
Private void Connection ()
{
This. skClient = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
IPEndPoint ie = new IPEndPoint (IPAddress. Parse (this. ip), this. port); // the IP address and port of the server
SkClient. Connect (ie );
Byte [] data = new byte [7];
This. Allowed en = this. skClient. Receive (data );
String s = Encoding. UTF8.GetString (data, 0, this. En en );
If (s! = "Success ")
{
Throw new Exception ("connection failed" + s );
}
}
# Endregion
}
}
Usage
Copy codeThe Code is as follows:
Public static readonly CacheSocket cac = new CacheSocket (2 );
Cac. Cmd ("send content ");