In fact, these things are available on the Internet, but they are relatively messy, and there are very few encapsulated classes. Share them here...
A socket server class and a Socket Client class can be used directly. A detailed call example is provided below.
It should be noted that the server class does not process multi-customer connections, but simply responds to single-customer connections.
In addition, it should be noted that, in particular, many new users may make mistakes, that is, server-class transaction processing is performed in the thread. At this time, the control on the interface cannot be accessed, and cross-thread access must be delegated.
Socket server class (socketserviceshelper. CS ):
Using system; using system. io; using system. net; using system. net. sockets; using system. text; using system. threading; using system. diagnostics; using system. text. regularexpressions; namespace usbcontrol {// <summary> // socket server class /// </Summary> public class socketserviceshelper {private socket socket1 = NULL; private socket socket2 = NULL; private thread listenthread = NULL; private int Port = 0; // listener Port /// <summary> /// constructor /// </Summary> /// <Param name = "Port"> listener port </param> Public socketserviceshelper (int port) {This. port = port;} // <summary> // start the service // </Summary> Public void startservices () {try {// obtain the IP address of the Local Machine IPaddress IP = IPaddress. parse (getip (); // Step 1 create the network endpoint ipendpoint myserver = new ipendpoint (IP, Port); // Step 2 create the socket Socket socket socket1 = new socket (addressfamily. interNetwork, so Ckettype. stream, protocoltype. TCP); // Step 3: bind the socket to the network endpoint socket1.bind (myserver); // create the listening thread listenthread = new thread (New threadstart (listenfunction); // start the listenthread. start () ;}catch (exception ex) {Throw ex ;}/// <summary> // method of listening, start in thread // </Summary> void listenfunction () {try {clsusbcontrol usbcl = new clsusbcontrol (); regchangenotice = new regchangenotice (); // Step 4 set the maximum number of customers Number of user-side connections socket1.listen (5); // loop detection client connection while (true) {// Step 5 check client connection socket2 = socket1.accept (); // step 6 determine the connection status if (socket2.connected) {// Step 7 receive client message byte [] clientdata = new byte [1024]; int I = socket2.receive (clientdata ); string removemsg = encoding. unicode. getstring (clientdata, 0, I ). split (New char [] {'|'}) [0]. split (New char [] {''}) [1]; // action based on message }}catch (exception ex) {Throw ex;} Fina Lly {// close the connection if (socket1.connected) {socket1.shutdown (socketshutdown. both); socket1.close ();} If (socket2.connected) {socket2.shutdown (socketshutdown. both); socket2.close ();}}} /// <summary> /// obtain the local IP address /// </Summary> /// <returns> </returns> private string getip () {string IPaddress = ""; process P = NULL; streamreader reader = NULL; try {processstartinfo start = new processstartinfo ("cmd. EXE "); start. filename = "ipconfig"; start. arguments = "/all"; start. createnowindow = true; start. redirectstandardoutput = true; start. redirectstandardinput = true; start. useshellexecute = false; P = process. start (start); reader = P. standardoutput; string line = reader. readline (); While (! Reader. endofstream) {If (line. tolower (). indexof ("ip address")> 0 | line. tolower (). indexof ("IPv4 address")> 0 | line. tolower (). indexof ("ip address")> 0) {int Index = line. indexof (":"); index + = 2; IPaddress = IPaddress + line. substring (INDEX) + ",";} line = reader. readline () ;}} catch (exception ex) {Throw ex;} finally {If (P! = NULL) {P. waitforexit (); p. Close () ;}if (reader! = NULL) {reader. Close () ;}return RegEx. Match (IPaddress. Equals ("")? IPaddress: IPaddress. substring (0, IPaddress. length-1), "[0-9] {1, 3 }\\. [0-9] {1, 3 }\\. [0-9] {1, 3 }\\. [0-9] {1, 3 }"). tostring ();}}}
Call example:
// Input the listening port during instantiation. The local IP address is automatically obtained.
Socketserviceshelper SSH = new socketserviceshelper (8881 );
// Start listening
Ssh. startservices ();
Socket Client class (socketclienthelper. CS ):
Using system; using system. io; using system. net; using system. net. sockets; using system. text; namespace BLL {// <summary> // Socket Client class // </Summary> public class socketclienthelper {private IPaddress IP = NULL; private int Port = 0; private Socket socket = NULL; /// <summary> /// constructor // </Summary> /// <Param name = "ip"> Server IP </param> /// <Param name = "Port"> server port </param> Public socketclienthelper (IP Address IP, int port) {This. IP = IP; this. port = port ;} /// <summary> /// send a message to the server /// </Summary> /// <Param name = "sendstr"> message content </param> /// <returns> </returns> Public String send (string sendstr) {try {layerparameter Lp = new layerparameter (); ipendpoint removeserver = new ipendpoint (IP, Port); socket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); socket. connect (Removeserver); // check the connection status if (socket. connected) {// convert the encoding byte [] BS = encoding. unicode. getbytes (sendstr); // send the message socket. send (BS, BS. length, 0); // disconnect the socket. shutdown (socketshutdown. both); // close the Socket socket. close (); Return "set successfully! ";} Else {return" failed to communicate with the client. It may be because the computer is not enabled or the client is not enabled! ";}} Catch (exception ex) {Throw ex ;}}}}
Call example:
// Input the Server IP address and Message Port when instantiating
Socketclienthelper Sch = new socketclienthelper (IPaddress. parse ("192.168.24.177"), 8881 );
// Send a message
Sch. Send ("Hello word! ");