The Code is as follows:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. net;
Using system. Threading;
Using system. net. Sockets;
Using system. Windows. forms;
Namespace mobilesocketctl
...{
// Client
Class mobilesocketclient: Control
...{
Private IPaddress hostipaddress;
Private ipendpoint server;
Private socket sock;
Private const int buffersize = 256;
Private byte [] buffer = new byte [buffersize];
Private Static manualresetevent connectdone = new manualresetevent (false );
Private Static manualresetevent senddone = new manualresetevent (false );
Public String serverip, SERVERPORT;
Private string shakecode;
Public Delegate void revdataevent (INT datalength, string databuf );
Public revdataevent clientrevevent;
Public mobilesocketclient ()
{
}
Public mobilesocketclient (string sip, string Sport)
{
Serverip = sip;
SERVERPORT = sport;
}
Public bool clientconnectserver (string sendshakecode)
{
Shakecode = sendshakecode. Trim ();
Try
{
Hostipaddress = IPaddress. parse (serverip. Trim ());
}
Catch
{
Return false;
}
Try
{
Server = new ipendpoint (hostipaddress, int32.parse (SERVERPORT ));
Sock = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Sock. beginconnect (server, new asynccallback (connectcallback), sock );
}
Catch (exception ee)
{
Return false;
}
Return true;
}
Private void connectcallback (iasyncresult AR)
{
Try
{
Socket Client = (socket) Ar. asyncstate; // get the status
Client. endconnect (AR );
Try
{
Byte [] bytedata = encoding. ASCII. getbytes (shakecode );
Sock. beginsend (bytedata, 0, bytedata. length, 0, new asynccallback (sendcallback), sock );
}
Catch (exception ee)
{
}
Thread thread = new thread (New threadstart (threadproc ));
Thread. Start (); // starts receiving data threads
Connectdone. Set (); // set the status of the specified event to terminate.
}
Catch
{
}
}
Private void sendcallback (iasyncresult AR)
{
Try
{
Socket Client = (socket) Ar. asyncstate;
Senddone. Set ();
}
Catch (exception ee)
{
}
}
Private void threadproc ()
{
Try
{
Sock. beginreceive (buffer, 0, buffersize, 0, new asynccallback (effececallback), sock );
}
Catch (exception ee)
{
}
}
Private void effececallback (iasyncresult AR)
{
Try
{
Socket Client = (socket) Ar. asyncstate;
Int bytesread = client. endreceive (AR); // ends the suspended asynchronous read. Returns the number of bytes received.
Stringbuilder sb = new stringbuilder ();
SB. append (encoding. ASCII. getstring (buffer, 0, bytesread); // store data
String content = sb. tostring (); // convert to string
If (clientrevevent! = NULL)
{
// Revdataevent d = new revdataevent (clientrevevent );
This. Invoke (clientrevevent, new object []... {bytesread, content });
}
SB. Remove (0, content. Length); // clear Sb content
Client. beginreceive (buffer, 0, buffersize, 0, new asynccallback (effececallback), client );
}
Catch (exception ee)
{
}
}
Public bool clientsendtext (string sendtext)
{
Try
{
String strsend = sendtext. Trim ();
Byte [] bytesend = encoding. ASCII. getbytes (strsend );
// Sock. Send (bytesend );
Sock. beginsend (bytesend, 0, bytesend. length, 0, new asynccallback (sendcallback), sock );
}
Catch
{
Return false;
}
Return true;
}
Public bool clientstopserver ()
{
Try
{
Sock. Close ();
Clientrevevent = NULL;
}
Catch
{
Return false;
}
Return true;
}
~ Mobilesocketclient ()
{
Clientstopserver ();
}
}
// Server
Class mobilesocketserver: Control
{
Private IPaddress hostipaddress;
Private ipendpoint server;
Private socket listeningsocket;
Private socket handler;
Private socket mysocket;
Private Static manualresetevent done = new manualresetevent (false );
Private const int buffersize = 256;
Private byte [] buffer = new byte [buffersize];
String IP, port;
String setupok;
Public Delegate void revdataevent (INT datalength, string databuf );
Public revdataevent serverrevevent;
Public mobilesocketserver (string serverip, string SERVERPORT)
{
IP = serverip;
Port = SERVERPORT;
}
Public bool setupserver (string setupokstr)
{
Setupok = setupokstr;
Try
{
Hostipaddress = IPaddress. parse (IP );
}
Catch {
Return false;
}
Try
... {// Use the Host IP address and port number of the combined service to form a connection point to the service.
Server = new ipendpoint (hostipaddress, int32.parse (port ));
// Create a socket object to establish a connection with the server
Listeningsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Listeningsocket. BIND (server); // bind the host port
Listeningsocket. Listen (50); // listening port, waiting for client connection request. 50 is the maximum number of incoming connections that can be accommodated in the queue.
// Accept extracts the first pending connection request from the connection request queue of the listening socket synchronously, and then creates and returns the new socket.
// Mysocket = listeningsocket. Accept ();
// A process can create one or more threads to execute some program code associated with the process. Use threadstart to delegate the program code to be executed by the thread.
Thread thread = new thread (New threadstart (threadproc ));
Thread. Start ();
}
Catch (exception ee )...{
Return false;
}
Return true;
}
Private void threadproc ()
...{
While (true)
...{
Done. Reset (); // set the status to non-terminated
Listeningsocket. beginaccept (New asynccallback (acceptcallback), listeningsocket); // starts an asynchronous operation to accept an incoming connection attempt
Done. waitone (); // blocks the current thread until the current thread receives a signal.
}
}
Private void acceptcallback (iasyncresult AR) // ar indicates the state of the asynchronous operation.
...{
Done. Set (); // set to terminate
Mysocket = (socket) Ar. asyncstate; // get the status
Handler = mysocket. endaccept (AR); // asynchronously accepts incoming connection attempts and creates a new socket to process remote host communication and obtain results
Try
...{
Byte [] bytedata = encoding. ASCII. getbytes (setupok );
// Call sendcallback to send data asynchronously,
Handler. beginsend (bytedata, 0, bytedata. length, 0, new asynccallback (sendcallback), Handler );
}
Catch (exception ee )...{
}
Thread thread = new thread (New threadstart (threadrev ));
Thread. Start ();
}
Private void sendcallback (iasyncresult AR)
{
Try
{
Handler = (socket) Ar. asyncstate; // get the status
Int bytessent = handler. endsend (AR); // end the suspended asynchronous sending and return the number of bytes sent to the socket.
}
Catch {}
}
Private void threadrev ()
{
Handler. beginreceive (buffer, 0, buffersize, 0, new asynccallback (readcallback), Handler );
}
Public void readcallback (iasyncresult AR)
{
Try
{
Int bytesread = handler. endreceive (AR); // end the suspended asynchronous read and return the number of bytes received.
Stringbuilder sb = new stringbuilder (); // variable character string for receiving data, which can be modified after being created by appending, removing, replacing, or inserting a character.
SB. append (encoding. ASCII. getstring (buffer, 0, bytesread); // append the string
String content = sb. tostring (); // convert to string
SB. Remove (0, content. Length); // clear Sb content
If (serverrevevent! = NULL) This. Invoke (serverrevevent, new object []... {bytesread, content });
Handler. beginreceive (buffer, 0, buffersize, 0, new asynccallback (readcallback), Handler );
}
Catch
{
}
}
Public bool serversendtext (string senddata)
{
Try
{
Byte [] bytesend = encoding. ASCII. getbytes (senddata );
Handler. beginsend (bytesend, 0, bytesend. length, 0, new asynccallback (sendcallback), Handler );
}
Catch {
Return false;
}
Return true;
}
Public bool serverstopserver ()
{
Try
{
Listeningsocket. Close ();
Serverrevevent = NULL;
}
Catch
{
Return false;
}
Return true;
}
~ Mobilesocketserver ()
{
Serverstopserver ();
}
}
}