我的问题是关于
BeginReceive()
方法。MSDN文章使用这两个函数来处理接收数据:private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static 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)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
在devarticles.com的教程中,BeginReceive
方法的最后一个参数被传递了null
,并解释了当我们处理多个套接字时,最后一个参数是有用的。现在我的问题是:
如果我们只使用单个套接字,那么将状态传递给
BeginReceive
方法有什么意义?这是为了避免使用类字段吗?似乎这样做没有太大意义,但也许我漏掉了什么。当处理多个套接字时,状态参数如何帮助?如果我调用
client.BeginReceive(...)
,那么所有数据都将从client
套接字读取吗?devarticles.com的教程使它听起来像在这个调用中:m_asynResult = m_socClient.BeginReceive (theSocPkt.dataBuffer,0,theSocPkt.dataBuffer.Length, SocketFlags.None,pfnCallBack,theSocPkt);
数据将从theSocPkt.thisSocket
套接字中读取,而不是从m_socClient
套接字中读取。在他们的示例中,两者是相同的,但如果情况不是这样会发生什么呢?
我真的看不出最后一个参数有什么用处,或者至少它如何在处理多个套接字时有所帮助。如果我有多个套接字,我仍然需要在每个套接字上调用BeginReceive
,对吧?
BeginReceive
的套接字对象相同,是吗?如果它们不同,那么可能会导致错误。 - IVladBeginReceive
回调函数中使用Socket client = state.workSocket;
。假设套接字A
在执行state.workSocket = B
后调用了BeginReceive
并传递了一个StateObject state
。只有当A == B
时,这才是有效的,对吧?我有点困惑,因为所有的示例都将相同的套接字传递给用于调用接收方法的状态,但它们没有明确说明两者必须相同。我认为它们应该相同,但我想确保这一点。 - IVlad