我正在使用带有阻塞套接字的 Synapse,并尝试简单地将文本发送到连接的客户端。代码如下:
var
SServer: TTCPBlockSocket;
SClient: TTCPBlockSocket;
implementation
//Create and initialize the Sockets.
procedure TForm1.FormCreate(Sender: TObject);
begin
SClient := TTCPBlockSocket.Create;
SServer := TTCPBlockSocket.Create;
SServer.Bind('127.0.0.1', '12345');
SClient.Connect('127.0.0.1', '12345');
end;
//Wait for connections.
procedure TForm1.FormShow(Sender: TObject);
begin
SServer.Accept;
//SServer.Listen; <- Could also work here?
end;
//Send the string to the connected server.
procedure TForm1.Button3Click(Sender: TObject);
begin
SClient.SendString('hi server');
end;
//Receive the string from the client with timeout 1000ms and write it into a memo
procedure TForm1.Button2Click(Sender: TObject);
var buf: string;
begin
Memo1.Lines.Add(SServer.RecvString(1000));
end;
首先,我单击 Button 3,然后单击 Button2。这样做,在 memo1 字段中没有写入任何内容。
这不应该工作吗?
#
****编辑:****
#
根据 skramads 的评论,我现在将它分成 2 个程序。开始了:
客户:
var
SClient: TTCPBlockSocket;
implementation
procedure TForm2.Button1Click(Sender: TObject);
begin
SClient.SendString(Edit1.Text);
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
SClient := TTCPBlockSocket.Create;
end;
procedure TForm2.FormShow(Sender: TObject);
begin
SClient.Connect('127.0.0.1','12345');
end;
服务器:
var
Form1: TForm1;
SSocket: TTCPBlockSocket;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
SSocket.Bind('127.0.0.1','12345');
SSocket.Listen;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Lines.Add(SSocket.RecvString(1000));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SSocket := TTCPBlockSocket.Create;
end;
尽管如此,这仍不能按预期工作。我只是那里没有数据。
有任何想法吗?