最近在做一个用socket建立并发服务器的模型,平台是C#,在建立服务器时考虑到利用线程池,异步操作。但是现在无从下手?
客户端的代码已经写出来了,具体如下:


public void StartClient()
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
socket.Connect(remoteEP);
Receive();//接收
sendThread = new Thread(new ThreadStart(Send));//启动发送。
sendThread.Start();
// Release the socket.
//socket.Shutdown(SocketShutdown.Both);
//socket.Close();
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
throw new Exception(e.Message);
}
}


private void Receive()
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = this.socket;
// Begin receiving the data from the remote device.
this.socket.BeginReceive(state.buffer, 0, state.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
private 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)
{
this.isReceive = true;
//处理接收的数据。
ReceivePacketManager.ReceivePacket(state.buffer);
client.BeginReceive(state.buffer, 0, state.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
ReceivePacketManager.isDataOver = true;
this.isReceive = false;
client.BeginReceive(state.buffer, 0, state.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}


public bool Send(ISendPacket data)
{
this.sendState = new StateObject();
this.sendState.workSocket = socket;
this.sendState.data = data;
this.sendState.buffer = SendPacketManager.SendByte(data);
if(!this.isReceive)
{
sendDone.Set();
return true;
}
return false;
}
private void Send()
{
//当收到信号就开始发送
sendDone.WaitOne();
socket.BeginSend(sendState.buffer, 0, sendState.buffer.Length, 0,
new AsyncCallback(SendCallback), sendState);
}
private void SendCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar;
Socket client = state.workSocket;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
if (bytesSent > 0)
{ //success send
if (!SendPacketManager.IsData)
{
sendDone.WaitOne();
}
else
{
state.buffer = SendPacketManager.SendByte(state.data);
client.BeginSend(state.buffer,0, state.BufferSize, 0, new AsyncCallback(SendCallback), state);
}
}
else
{ //failed;
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}