在Delphi 2010中使用socket发送和接收文本



我对Delphi 2010不太熟悉,并且在使用组件ClientSocket和ServerSocket时遇到麻烦。问题很简单:我正在尝试使用以下代码从客户端发送文本到服务器:

cliente.Socket.SendText('call');
在服务器端,我写了以下代码:
procedure TForm6.ServerClientRead(Sender: TObject; Socket: TCustomWinSocket);
var
s: string;
begin
s:=Socket.ReceiveText;
if s = 'call' then
begin
showmessage('Client is Calling');
end;
end;

但是,服务器不显示消息。能再帮我一次吗?

在D2009+中,SendText()ReceiveText()不能正确使用Unicode字符串。

直接使用SendBuf()ReceiveBuf()为宜。

话虽如此,TClientSocketTServerSocket已经被弃用很长时间了。您应该使用不同的组件集,例如Indy(也随Delphi附带),例如:

IdTCPClient1.IOHandler.WriteLn('call');

procedure TForm6.IdTCPServer1Execute(AContext: TIdContext);
var
  s: string;
begin
  s := AContext.Connection.IOHandler.ReadLn;
  if s = 'call' then
  begin
    // TIdTCPServer is a multi-threaded component,
    // but ShowMessage() is not thread-safe...
    Windows.MessageBox(0, 'Client is Calling', '', MB_OK);
  end;
end;

最新更新