考虑代码:
class UPDServer {
//start listener
public void start() {
UdpClient listener = new UdpClient(this._porta);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 10000);
State s = new State();
s.listener = listener;
s.ipEndPoint = ipEndPoint;
// begin to listen again
listener.BeginReceive(new AsyncCallback(ReceiveCallback), s);
}
//receive data
public void ReceiveCallback(IAsyncResult ar)
{
// we got data
State s = (State)(ar.AsyncState);
Byte[] received = e.escuta.EndReceive(ar, ref e.ipEndPoint);
string text = ""; = Encoding.ASCII.GetString(received);
// ... do somenthing with text
// begin to listen again
s.listener.BeginReceive(new AsyncCallback(ReceiveCallback), e);
}
}
在上面的代码中,EndReceive 和下一个 BeginReceive 之间有一个时间跨度,没有人在听,我认为如果在这个时间跨度内有消息,它将丢失。
好吧,我想有某种缓冲区,但即使缓冲区在没有人收听消息的时间跨度内填满,消息也会丢失。
我记得有人说这可以通过在同一端点多次调用 BeginReceive 来解决,所以我尝试了这个:
for( int x = 0; x < 5;x++) {
escuta.BeginReceive(new AsyncCallback(ReceiveCallback), e);
}
奇怪的是,在同一个套接字上调用 begin receive 不会引发错误,但每次收到一条消息时,所有五个 beginReceive 都会触发并且所有五个都收到相同的消息。
有没有办法改进代码?