C # Socket thread

Source: Internet
Author: User

The original version is as follows: Click to open the link. But I haven't made any adjustments, so I consulted my colleague Xiang Ge and finally got it done!

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 {Socket 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, which can represent a service for Socket communication. // There Is A Parse () method in the IPAddress class. You can convert the decimal IP representation of the vertex into IPAddress class IPEndPoint ipep = new IPEndPoint (IPAddress. parse (strIP), nPort); // create a socket instance // ProtocolType is used when the socket instance is created here. tcp indicates the establishment of a connection-oriented (TCP) Socket vsServerSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); try {// bind the created socket with IPEndPoint to vsServerSocket. bind (ipep);} catch (SocketException ex) {MessageBox. show ("Connect Error:" + ex. message); return;} Byte [] buffer = new Byte [1024]; // set the socket to the listening mode vsServerSocket. listen (10); // loop listener 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) {// connect to the server // use the ThreadStart delegate to tell the sub-Thread how to execute vsClientThread = new Thread (new ThreadStart (ClientHandle); vsClientThread. start () ;}// when the form is closed, the client process private void Client_FormClosing (object sender, FormClosingEventArgs e) {KillProcess ();} // kill the client process private void KillProcess () {Process [] processes = Process. getProcessesByName ("SocketClient"); foreach (Process in processes) {process. kill (); break ;}}}}
Server 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 attribute, namespace: System. windows. forms // gets a value that indicates whether the caller must call the Invoke method when calling the method of the control, because the call is located in a thread other than the thread where the control is created. If (tBoxServerSend. InvokeRequired = true) {// Control. Invoke method (Delegate) // execute the specified Delegate on the thread that owns the basic window handle of this Control. PassString d = new PassString (SeverSendData); this. invoke (d, new object [] {strMsg});} else {tBoxServerSend. text = strMsg;} private void SeverRecvData (string strMsg) {if (tBoxServerReceive. invokeRequired = true) {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); // bind the created socket to IPEndPoint. try {vsServerSocket. bind (ipep);} catch (Exception ee) {MessageBox. show (ee. toString (); return;} // sets the socket to the listening mode vsServerSocket. listen (10); int bufLen = 0; // loop listener while (true) {// Receive the connected Socket vsClientSocket = vsServerSocket on the Socket. accept (); try {Byte [] buffer = new Byte [1024]; // receives 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 the 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 = new 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 ThreadStart (ServerStart); vsServerThread. start () ;}// when the form is closed, the client process private void Server_FormClosing (object sender, FormClosingEventArgs e) {KillProcess ();} // kills the 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 messages to the server, or the server can send messages to the client.

Disadvantages:

Currently, the server can only connect to one client.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.