如何将文本从 Indy TCPServer 发送到 TCPClient
How to send text from Indy TCPServer to TCPClient
我需要对使用 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;
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?
我需要对使用 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;
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?