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 ();