Explanation of socket communication in C # (1): Connection implementation

Source: Internet
Author: User

Step 1: Implement connection

Client connection code:

Private void connect2server ()

{

Socket clientsocket;

// Server address

IPaddress IP = IPaddress. parse ("192.168.1.136 ");

// Server node ipendpoint IEP = new ipendpoint (IP, 9004 );

// Communication instance clientsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );

// Connect to clientsocket. Connect (IEP );

}

The client connects to port 9004 of the server through socket.

 

The server accepts the connection code:

Public void startlistening ()

{

// Obtain the local IP Address

Socket serversocket; iphostentry iphost = DNS. gethostentry (DNS. gethostname (); hostip = iphost. Addresslist [0];

// Switch Control

Bool flag = true; try {ipendpoint IEP = new ipendpoint (hostip, 9004 );

Serversocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); serversocket. BIND (IEP );

// A maximum of 100 serversocket. Listen (100); // If a client is connected, add it to the queue while (FLAG) {// check whether the listener has a client connection

Clientsocket = serversocket. Accept (); If (clientsocket! = NULL) {string STR = clientsocket. remoteendpoint. tostring (); string [] ipstr = Str. Split (':');

String clientip = ipstr [0];

MessageBox ("client:" + clientip + "connect to server ");

}

} Catch (exception e ){

MessageBox. Show ("connection error:" + E. Message );}

}

The server starts the socket and listens on whether a client is in. If yes, add it to the queue. Generally, to allow the client and server to respond to other events, place them in an independent thread. Similar to the following code:

Thread _ createserver;

_ Createserver = new thread (New threadstart (startlistening); _ createserver. isbackground = true; _ createserver. Start ();

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.