【问题标题】:How to send text from Indy TCPServer to TCPClient如何将文本从 Indy TCPServer 发送到 TCPClient
【发布时间】:2019-04-03 20:03:41
【问题描述】:

我需要在使用 TIdTCPServer 和 TIdTCPClient 制作的聊天应用中进行简单修复。请,无需额外代码,仅用于发送和接收文本。

procedure TServerApp1.Button1Click(Sender: TObject);
var
  AContext : TIdContext;
begin
  AContext.Connection.Socket.Write(length(newMSG.Text));
  AContext.Connection.Socket.Write(newMSG.Text);
end;

【问题讨论】:

    标签: delphi indy


    【解决方案1】:

    TIdTCPServer 有一个 Contexts 属性,其中包含已连接客户端的列表。您必须锁定并遍历该列表以查找要发送到的客户端。例如:

    procedure TServerApp1.Button1Click(Sender: TObject);
    var
      Buf: TIdBytes;
      List: TIdContextList;
      Context: TIdContext;
      I: Integer;
    begin
      // this step is important, as Length(newMSG.Text) will not
      // be the actual byte count sent by Write(newMSG.Text)
      // if the text contains any non-ASCII characters in it!
      Buf := ToBytes(newMSG.Text, IndyTextEncoding_UTF8);
    
      List := IdTCPServer1.Contexts.LockList;
      try
        for I := 0 to List.Count-1 do
        begin
          Context := TIdContext(List[I]);
          if (Context is the one you are interested in) then
          begin
            Context.Connection.IOHandler.Write(Length(Buf));
            Context.Connection.IOHandler.Write(Buf);
            Break;
          end;
        end;
      finally
        IdTCPServer1.Contexts.UnlockList
      end;
    end;
    

    但是,我不建议像这样直接向客户端发送消息。这可能会导致可能破坏您的通信的竞争条件。更安全的选择是为每个客户端提供自己的线程安全队列,您可以在需要时将消息推送到该队列中,然后您可以让TIdTCPServer.OnExecute 事件处理程序在安全的情况下发送排队的消息。请参阅my answer 以获取以下问题的示例:

    ¿How can I send and recieve strings from tidtcpclient and tidtcpserver and to create a chat?

    【讨论】:

    • “LockList”和“UnlockList”是干什么用的?
    • @DJMixRhymez TIdTCPServer 是一个多线程组件。 Contexts 属性是一个TThreadList,它是一个受TCriticalSection 保护的TList。您必须锁定 CS 才能访问列表,然后在完成后解锁。
    • tidtcpclient如何接收服务器发送的数据
    • @DJMixRhymez 要从服务器读取未经请求的消息,您需要在客户端运行一个工作线程并让它不断地从套接字读取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多