0

我的服务器表单有 stringgride 只接受 4 个 tcp 连接用户为此,我将 udpclient 放在我的服务器中,将 udpserver 放在客户端中

在服务器形式的 tcp-onconnect 事件中:

   //Server Side has udp client
 procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin

      //when fifth user want to connect to tcpserver 
      //server first ensure at list one of the 4 connected user in grid has disconnected
      //by send udp broadcast to 4 user
      //but in this timeout None of these users do not respond , Although still connected

      IdUDPClient1.Broadcast('IP', 1718);
      For i:=1 To 4 Do
      begin
       IPList.Add(IdUDPClient1.ReceiveString(200););
      end;
end;


//Client Side has udp server
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
    ABinding: TIdSocketHandle);
begin
 //
 ip:=GetipAddress();
 ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, ip[1], Length(ip));
end;

我在客户端运行 ethereal 以检查网络并看到 udp 消息从服务器发送到客户端,但客户端没有响应。

请帮助我什么是我的代码问题

4

1 回答 1

1

您的TIdUDPServer.OnUDPRead事件处理程序没有正确的签名,甚至没有关闭。TIdUDPServer根本不使用TIdPeerThread,只会TIdTCPServer使用。你需要做更多这样的事情:

服务器:

procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
  //when fifth user want to connect to tcpserver 
  //server first ensure at list one of the 4 connected user in grid has disconnected
  //by send udp broadcast to 4 user
  //but in this timeout None of these users do not respond , Although still connected

  IPList.Clear;
  IdUDPServer1.Broadcast('IP', 1718);
  Sleep(1000);
end;

procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
  S: String;
begin
  if AData.Size > 0 then
  begin
    SetLength(S, AData.Size);
    AData.ReadBuffer(S[1], AData.Size);
    IPList.Add(S);
  end;
end;

客户:

procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
  S: String;
begin
  if AData.Size > 0 then
  begin
    SetLength(S, AData.Size);
    AData.ReadBuffer(S[1], AData.Size);
  end;
  if S = 'IP' then
  begin
    S := ABinding.IP;
    if (S = '') or (S = '0.0.0.0') then
      S := GStack.LocalAddress;
    ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, S[1], Length(S));
  end;
end;
于 2013-05-15T17:25:08.260 回答