private void StartClient()
{
// Connect to a remote device.
try
{
IPHostEntry ipHostInfo = Dns.Resolve(this.m_strServerIP);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, this.m_nServerPort);
// Create a TCP/IP socket.
this.m_clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
this.m_clientSocket.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), this.m_clientSocket);
}
catch (Exception e)
{
this.ReportError("StartClient found a error:\r\n" + e.ToString());
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
this.m_bConnected = true;
this.Connected();
Receive(client);
private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
state.buffer=new byte[BufferSize];
// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
this.ReportError("Begin Receive found a error:\r\n" + e.ToString());
}
}
protected void ReceiveCallback( IAsyncResult ar )
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
byte[] data=new byte[bytesRead];
for(int i=0;i<bytesRead;i++)
{
data[i]=state.buffer[i];
}
this.ReceiveMsg(data);
// Get the rest of the data.
client.BeginReceive(state.buffer,0,BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
this.DisConnected();
this.close();
}
}
catch
{
//this.ReportError("Receive msg found a error:\r\n" + e.ToString());
this.close();
this.DisConnected();
}
}
private void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
this.SendBack();
}
catch (Exception e)
{
ReportError(e.ToString());
}
}
}
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Receive buffer.
public byte[] buffer;
}
}