0

谁能指导我我在这里做错了什么,或者有没有更好的方法来执行这项任务?

它是一个聊天应用程序,使用TIdUDPServer我从服务器获取客户端信息现在我想将文本发送到从TListBox. 我有两个列表,一个是可视TListBox的,其中仅存储用户名。而另一个定义为 FClient: TList其中包含从服务器发送的记录(两者都是更新的 OnUDPRead 事件)。

Mylibarary 定义如下。

tcommand=(cmd_login,cmd_user,cmd_add,cmd_data,cmd_remove,cmd_logout);

TPacket = record

  command_id:tcommand;
  username  :string;
  ip        :string;
  i_ip      :string;
  port      :word;
  msgpacket :string;

end;

ppacket=^tpacket;

tudp_protocol=class

  buffer:tidbytes;
  packet:ppacket;
  //index:word;

procedure Login;
procedure Add;
procedure Msg;
procedure Logout;
procedure ExtractLogin;
procedure ExtractAddRemoveUser;
procedure ExtractMessage;
procedure ExtractLogout;
procedure ExtractUser;

constructor Create ( var ARecord: PPacket );
constructor Extract (var ARecord: PPacket; var ABuffer : TBytes);
end;

下面的代码在发送点击时触发。

    procedure TForm2.SendClick(Sender: TObject);
    var
 player,peer:tudp_protocol;
 p,packet:ppacket;
 selected,i,index:integer;
 peerip:string;
 peerport:word;
 name:string;
begin

  new(p);
  new(packet);

  selected:=0;

  p.command_id:=cmd_data;
  p.msgpacket:=edit1.Text;

  memo1.Lines.Add(p.msgpacket);

  player:=tudp_protocol.Create(p);//encoding data here from string to byte array 

      if ListBox1.ItemIndex = -1 then
      begin
        ShowMessage('Username not selected');
        Exit;
      end
      else
      begin
        selected := ListBox1.ItemIndex;
        name := ListBox1.Items[selected];
        // comparing the listbox username with fclient list username
        for index := 0 to FClient.Count - 1 do
        begin
          packet := FClient.Items[index];
          if (CompareStr(packet.username, name) = 0) then
          begin
            peerip := packet.ip; //getting external ip of matched name   
            peerport := packet.port; // external port
            client.SendBuffer(peerip, peerport, player.buffer);// encoded data sent
          end;
        end;
      end;
    end;


procedure TForm2.clientUDPRead(AThread: TIdUDPListenerThread;
  AData: array of Byte; ABinding: TIdSocketHandle);

  var

  buffer:tidbytes;
  protocol:tudp_protocol;
  packet:ppacket;

begin

  new(packet);
  setlength(buffer,length(adata));
  move(adata[0],buffer[0],length(adata));

  protocol:=tudp_protocol.Extract(packet,buffer);

  listbox1.AddItem(packet.username,nil);
  fclient.Add(packet);



  memo1.Lines.Add(packet.msgpacket);

end;

//------------------------------------------------------------------------------

procedure TForm2.FormCreate(Sender: TObject);
begin

  fclient:=tlist.Create;
  fclient.Capacity:=10;

end;
4

0 回答 0