The original version was this: Click to open the link. But has not been adjusted well, so I consulted a colleague Xiang elder brother, the final preliminary fix!
Client code:
Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.windows.forms;using system.net.sockets;using System.Threading; Using system.net;using system.diagnostics;namespace socketclient{public partial class Client:form {so Cket Vsserversocket; Thread Vsclientthread; String StrIP = "127.0.0.1"; public delegate void Passstring (string strMsg); int nport = 9001; Public Client () {InitializeComponent (); public void Setsenddata (string strMsg) {if (tboxclientsend.invokerequired = = True) {passstring d = new passstring (setsenddata); This. Invoke (d, new object[] {STRMSG}); } else {tboxclientsend.text = STRMSG; }} public void Setrecvdata (string strMsg) {iF (tboxclientreceive.invokerequired = = True) {passstring d = new passstring (setrecvdata); This. Invoke (d, new object[] {STRMSG}); } else {tboxclientreceive.text = STRMSG; }} private void Clienthandle () {string strrecv = string. Empty; IPEndPoint is actually an IP address and port binding, can represent a service, used for socket communication. There is a Parse () method in the IPAddress class that converts the dotted decimal IP representation to the IPAddress class IPEndPoint Ipep = new IPEndPoint (Ipaddress.parse (StrIP), Nport); Create a socket instance//when created here, use PROTOCOLTYPE.TCP to create a connection-oriented (TCP) socket vsserversocket = new Socket (addressfamil Y.internetwork, SocketType.Stream, protocoltype.tcp); try {//binds the created socket to the IPEndPoint vsserversocket.bind (IPEP); } catch (SocketException ex) {MessageBox.Show ("Connect Error:" + ex. Message); Return } byte[] buffer = new byte[1024]; Set socket to listen mode Vsserversocket.listen (10); Loop listen while (true) {//Receive server information int buflen = 0; try {Socket vsclientsocket = vsserversocket.accept (); buflen=vsclientsocket.receive (buffer); Vsclientsocket.send (Encoding.ASCII.GetBytes ("AAAAA"), 5, Socketflags.none); } catch (Exception ex) {MessageBox.Show ("Receive Error:" + ex.) Message); } STRRECV = Encoding.ASCII.GetString (buffer, 0, Buflen); Setrecvdata (STRRECV); Vsclientsocket.shutdown (Socketshutdown.both); Vsclientsocket.close (); }}//Send data private void BTNsend_click (object sender, EventArgs e) {byte[] data = new byte[1024]; string ss = Tboxclientsend.text; Socket centerclient = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); IPEndPoint gsserver = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 9002); Centerclient.connect (Gsserver); Centerclient.send (Encoding.ASCII.GetBytes (ss)); Centerclient.close (); private void Client_load (object sender, EventArgs e) {///connection server//through ThreadStart delegate to tell the child line What method vsclientthread = new Thread (new ThreadStart (Clienthandle)); Vsclientthread.start (); }//When the form is closed kill client process private void Client_formclosing (object sender, FormClosingEventArgs e) { KillProcess (); }//Kill client process private void KillProcess () {process[] processes = Process.getprocessesbyname ( "Socketclient"); foreach (process process in processes) {process. Kill (); Break } } }}
Service-Side code:
Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.windows.forms;using system.threading;using System.Net.Sockets; Using system.net;using system.diagnostics;namespace socketserver{public partial class Server:form {Thread Vsserverthread; Socket Vsserversocket; String StrIP = "127.0.0.1"; public delegate void Passstring (string strMsg); int nport = 9002; Public Server () {InitializeComponent (); private void Seversenddata (string strMsg) {//control.invokerequired property, namespace: system.windows.f Orms//Gets a value that indicates whether the caller must call the Invoke method when making a method call to the control, because the call is in a thread other than the one on which the control is created. if (tboxserversend.invokerequired = = True) {//control.invoke method (Delegate)//in the owning Executes the specified delegate on the thread of this control's underlying window handle. Passstring d = new Passstring (SeVersenddata); This. Invoke (d, new object[] {STRMSG}); } else {tboxserversend.text = STRMSG; }} private void Severrecvdata (string strMsg) {if (tboxserverreceive.invokerequired = = TR UE) {passstring d = new passstring (severrecvdata); This. Invoke (d, new object[] {STRMSG}); } else {tboxserverreceive.text = STRMSG; }} private void ServerStart () {string strrecv = string. Empty; Create IPEndPoint instance IPEndPoint Ipep = new IPEndPoint (Ipaddress.parse (StrIP), nport); Create a socket Vsserversocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Binds the created socket to IPEndPoint with the try {vsserversocket.bind (IPEP); } catch (ExceptIon ee) {MessageBox.Show (EE). ToString ()); Return }//Set socket for listening mode Vsserversocket.listen (10); int buflen = 0; Loop listen while (true) {//Receive access connections on sockets socket Vsclientsocket = Vsserve Rsocket.accept (); try {byte[] buffer = new byte[1024]; Receive the information sent by the client on the socket Buflen = vsclientsocket.receive (buffer); Vsclientsocket.send (Encoding.ASCII.GetBytes ("AAAAA"), 5, Socketflags.none); if (Buflen = = 0) continue; Decodes a sequence of bytes from a specified byte array into a string. STRRECV = Encoding.ASCII.GetString (buffer, 0, Buflen); Severrecvdata (Strrecv.tostring ()); } catch (Exception ex) {MesSagebox.show ("Listening Error:" + ex.) Message); Vsclientsocket.close (); Vsserversocket.close (); }}} private void Btnsend_click (object sender, EventArgs e) {byte[] data = NE W byte[1024]; string ss = Tboxserversend.text; Socket centerclient = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); IPEndPoint gsserver = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 9001); Centerclient.connect (Gsserver); Centerclient.send (Encoding.ASCII.GetBytes (ss)); Centerclient.send (Encoding.ASCII.GetBytes (ss)); Thread.Sleep (100); Centerclient.close (); } private void Server_load (object sender, EventArgs e) {vsserverthread = new Thread (New THREADST Art (ServerStart)); Vsserverthread.start (); }//Kill client process when form closes private void Server_formcloSing (object sender, FormClosingEventArgs e) {killprocess (); }//Kill client process private void KillProcess () {process[] processes = Process.getprocessesbyname ( "Server"); foreach (process process in processes) {process. Kill (); Break } } }}
The effect is as follows:
The client can send a message to the server, and the server can send a message to the client.
Disadvantages:
Now the server can only connect to one client
The above is the content of the C # Socket thread, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!