【问题标题】:Synapse: Cannot receive data from SocketSynapse:无法从 Socket 接收数据
【发布时间】:2010-11-18 06:45:56
【问题描述】:

我正在使用带有阻塞套接字的 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;

首先,我单击按钮 3,然后单击按钮 2。这样一来,便不会在 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;

不过,这并没有按预期工作。我只是没有得到那里的数据。

有什么想法吗?

【问题讨论】:

    标签: delphi sockets synapse


    【解决方案1】:

    您应该阅读套接字通信的工作原理,例如here(英语)或here(德语)。简而言之:您在服务器端listen() 上的套接字本身不用于通信,您必须调用accept() 为客户端打开另一个套接字作为伙伴,并使用该套接字发送和接收数据。侦听套接字仅用于接受来自其他客户端的其他连接,然后您可以使用这些连接在一台服务器和多个客户端之间进行并行通信。

    也许您应该首先检查一个简单的客户端/服务器演示应用程序。无论您使用 Synapse、Indy 还是低级 API 编程,原理都是一样的。

    【讨论】:

    • 好的,现在可以了。仍然,loadfromstream 不起作用。
    • 你是什么意思,在你的问题中没有提到LoadFromStream?请澄清。
    【解决方案2】:

    如果你把它分成两个独立的程序,那么它会更好地工作。阻塞调用就是这样做的……它们阻塞直到它们完成。

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2015-07-22
      • 2018-04-20
      • 2015-07-31
      • 2021-11-19
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多