Receive (Socket Client)
{
// construct the container state.
stateobject state = New stateobject ();
state. worksocket = client;
// receives data from a remote target.
client. beginreceive (state. buffer, 0 , stateobject. buffersize, 0 ,
New asynccallback (effececallback ), state);
}
private static void effececallback (iasyncresult AR)
{
// obtain the state and socket objects from the asynchronous State object of the input parameter
stateobject state = (stateobject) ar. asyncstate;
Socket Client = state. worksocket;
// read data from a remote device
int bytesread = client. endreceive (AR);
If (bytesread > 0 )
{< br> /// data, storage.
state. SB. append (encoding. ASCII. getstring (state. buffer, 0 , bytesread ));
// Continue reading.
Client. beginreceive (State. buffer, 0 , Stateobject. buffersize, 0 ,
New Asynccallback (effececallback), State );
}
Else
{
// All data has been read.
If (State. sb. Length > 1 )
{
Response = State. sb. tostring ();
}
// Indicates that all data has been read.
Receivedone. Set ();
}
}
Send data:
Code
Private Static Void Send (Socket Client, string data)
{
// Format conversion.
Byte [] Bytedata = Encoding. ASCII. getbytes (data );
// Start sending data to a remote device.
client. beginsend (bytedata, 0 , bytedata. length, 0 ,
New asynccallback (sendcallback ), client);
}
Private Static VoidSendcallback (iasyncresult AR)
{
//Obtain the socket from the State object
Socket Client=(Socket) Ar. asyncstate;
// data transmission is completed.
int bytessent = client. endsend (AR);
console. writeline ( " sent {0} bytes to server. " , bytessent );
//Indicates that the data has been sent and the main thread continues.
Senddone. Set ();
}