关于UDP的发送和接收给你一段代码:
发送:
var
MyStream: TMemoryStream;
TmpStr,MyWords:string;
begin
if FChatDCom<>nil then
begin
TransUDP.ReportLevel := Status_Basic;
TransUDP.RemoteHost := FChatDCOM.GetUserIP(PChar(Trim(TV_Status.Selected.Text)));
//将用户IP地址赋给UDP
TransUDP.RemotePort := FPort;
MyWords:=InputBox('输入你想说的话','你想对'+TV_Status.Selected.Text+'说:','');
TmpStr :=TV_Status.Selected.Text+'对你说:'+MyWords;
MyStream := TMemoryStream.Create;
try
MyStream.Write(TmpStr[1], Length(TmpStr));
TransUDP.SendStream(MyStream);
finally
MyStream.Free;
end;
end
else
ShowMessage('请先登录到服务器上!');
end;
接收:
var
MyStream: TMemoryStream;
TmpStr: array of char;
begin
MyStream := TMemoryStream.Create;
try
TransUDP.ReadStream(MyStream);
MyStream.Seek(0,0);
SetLength(tmpStr,MyStream.size);
MyStream.Read(TmpStr[0],MyStream.Size);
finally
MyStream.Free;
end;
//判断信息的级别
case TmpStr[0] of
'1':begin
MemoSaying.Lines.Add(copy(string(TmpStr),2,length(string(TmpStr))));
GetUserList;
end;
'0':begin
MemoSaying.Lines.Add(copy(string(TmpStr),2,length(string(TmpStr))));
GetUserList;
end;
else
begin
ShowMessage(string(tmpStr));
end;
end;