任何人都可以指导我,我在这里做错了什么,或者有更好的方法来执行这项任务吗?
使用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;