1

我使用 Delphi XE2 和 Indy10 UDP 协议。如果我使用 ReceiveBuffer 方法,我无法在客户端接收服务器回显。尽管我从服务器向客户端发送了非常小的回显消息,但我得到了“套接字错误 # 10040”。说明我的问题的控制台应用程序如下。提前致谢。

program Project1;
{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, IdGlobal, IdBaseComponent, IdComponent, IdSocketHandle,
  IdUDPClient, IdUDPServer, IdUDPBase, IdStack;

type
  TUDP_Serv = class(TIdUDPServer)
    procedure udpSvUDPRead(AThread: TIdUDPListenerThread;
      AData: TIdBytes; ABinding: TIdSocketHandle);
  end;
var
  udpServer: TUDP_Serv;
  udpCl: TIdUDPClient;
  bSnd, bRcv: TBytes;
  s: string;
  k: integer;
//==============================================================================
procedure TUDP_Serv.udpSvUDPRead(AThread: TIdUDPListenerThread; AData: TIdBytes;
  ABinding: TIdSocketHandle);
begin
writeln(' Server read: ' + ToHex(AData, length(AData)));
with ABinding do SendTo(PeerIP, PeerPort, AData);
end;
//==============================================================================
begin
try
  udpServer := TUDP_Serv.Create;
  with udpServer do begin
    OnUDPRead := udpSvUDPRead; DefaultPort := 20001; BufferSize := 2048;
    ThreadedEvent := true; Active := True;
    if Active then writeln('Server started on port: ' + IntToStr(DefaultPort));
  end;
  udpCl := TIdUDPClient.Create;
  with udpCl do begin
    BufferSize := 2048; Host := '127.0.0.1'; Port := 20001;
  end;
  SetLength(bSnd, 5); bSnd[0] := $31; bSnd[1] := $0;
  bSnd[2] := $33; bSnd[3] := $0; bSnd[4] := $0;
  repeat
    writeln(' Client send: ' + ToHex(bSnd, length(bSnd)));
    with udpCl do SendBuffer(Host, Port, bSnd); sleep(100);
    try
      k := udpCl.ReceiveBuffer(bRcv, 10);
      if k > 0 then writeln(' Client read: ' + ToHex(bRcv, length(bRcv)));
    except
      on E: exception do begin
        writeln(Format(' Client read err: %s',[E.Message]));
      end;
    end;
    readln(s);
  until s <> '';
except
  on E: Exception do begin
    Writeln(E.ClassName, ': ', E.Message); readln(s);
  end;
end;
end.

屏幕输出:

Server started on prot: 20001
 Client send: 3100330000
 Server read: 3100330000
Client read err: Socket Error # 10040
Message too long.
4

1 回答 1

0

10040 is WSAEMSGSIZE, which means the buffer you tried to receive into was smaller than the actual size of the message that was received.

You are not allocating any memory for bRcv before calling ReceiveBuffer(), so you are trying to receive into a 0-byte buffer, hense the error. You need to pre-allocate bRcv to at least the same size as your messages, if not larger.

ReceiveBuffer() does not allocate a new TBytes for each received message. You have to allocate the buffer yourself beforehand and then ReceiveBuffer() will merely fill it in, returning how many bytes were actually received into it.

于 2013-04-01T22:16:23.213 回答