Delphi中的UDP服务器和客户端客户端、服务器、Delphi、UDP

2023-09-07 13:34:42 作者:无关风月

我正在制作一个 UDP C/S.我对服务器每秒可以接收的数据数量有疑问.

I am making a UDP C/S. I am having a problem with number of data the server can receive per second.

我已经测试了将 10、100、1000 条数据消息批量发送到服务器,10、100 条接收没有问题.发送 1000 个时,只收到 300 ~ 400 个.所有测试都在本地完成.

I have tested sending batches of 10, 100, 1000 data messages to the server, 10, 100 received without a problem. when sending 1000, only 300 ~ 400 received. All tests done on locally.

我尝试使用 ICS 的 twsocket 和 Synapse 的 tudpblocksocket 来实现服务器.两者都出现了上述相同的问题.

I have tried implement the server using both ICS's twsocket and Synapse's tudpblocksocket. Both turned out with same problem above.

能否向我解释为什么会发生这种情况,以及如何提高服务器性能.

Could any explain to me why this happens, and how could I improve the server performance.

使用 TUDPBlockSocket 的代码

Code using TUDPBlockSocket

...

while not Terminated do
begin
  try
    sz := FUDPServer.WaitingData;
    if sz > 0 then
    begin
      FUDPServer.RecvBuffer(mem.Memory, sz);
      mem.Seek(0, 0);
      AMessage := fFormats.ReadFromStream(mem);
      DoMessageReceived(FUDPServer.RemoteSin.sin_addr, AMessage);
    end; 

  finally

  end;
end;

...

使用 ICS 的代码

...

procedure TShapeServer.WSocketDataAvailable(Sender: TObject; ErrCode: Word);
...
begin
  SrcLen := SizeOf(Src);
  stream := TMemoryStream.Create;
  stream.SetSize(INT_BUFFER_SIZE);
  Inc(fMessageReceived);  
  try
    Len    := FUDPServer.ReceiveFrom(stream.Memory, stream.size, Src, SrcLen);
    if (FSenderAddr.S_addr = INADDR_ANY) or
       (FSenderAddr.S_addr = Src.Sin_addr.S_addr) then
    begin

      while stream.Position < Len do
      begin
        try
          AMessage := fFormats.ReadFromStream(stream);
          DoMessageReceived(Src.Sin_addr, AMessage);
        except
          break;
        end;
      end;

    end;

  finally
    stream.Free;
  end;
end;
...

推荐答案

UDP 不保证消息传递 - 如果缓冲区中没有位置,数据包会毫不犹豫地丢弃.如果您需要保证交付,请使用 TCP 并在 TCP 之上构建基于消息的通信方案.或者使用我们已有的 MsgConnect 产品.十字军注意事项:MsgConnect 有一个开源版本.

UDP doesn't guarantee message delivery - if there's no place in the buffer, the packet is dropped without hesitation. If you need guaranteed delivery, use TCP and build a message-based communication scheme on top of TCP. Or use our MsgConnect product which already has it. Note for crusaders: MsgConnect has an open-source version.