我使用Indy和Lazarus编写套接字应用程序。这是我的代码如下。 套接字连接正确,但在向服务器发送数据包时,它没有收到任何内容。我肯定错过了什么。谢谢!
procedure TSocket.IdTCPServer1Execute(AContext: TIdContext);
var
Socket_Receive_Buffer: TIdBytes;
Socket_Input_Length: integer;
begin
with AContext.Connection do
begin
IOHandler.ReadBytes(Socket_Receive_Buffer, 1024, False);
ShowMessage('Getting bytes');
Socket_Input_Length := Length(Socket_Receive_Buffer);
if Socket_Input_Length > 0 then
begin
Writeln('received something: nb bytes = '+IntToStr(Socket_Input_Length));
end;
end;
end;
function TSocket.Open: boolean;
begin
if Settings.SocketModeRadioGroup.ItemIndex = 0 then
begin
IdTcpServer1 := TIdTCPServer.Create(nil);
IdTCPServer1.OnExecute := @IdTCPServer1Execute;
IdTCPServer1.OnConnect := @IdTCPServer1Connect;
IdTCPServer1.OnDisconnect := @IdTCPServer1Disconnect;
IdTcpServer1.DefaultPort := StrToInt(Settings.SocketPortEdit.Text);
IdTcpServer1.MaxConnections := 1;
IdTCPServer1.Bindings.Add.IPVersion := Id_IPv4;
IdTcpServer1.Active := True;
Writeln('Server started. Listening for messages');
end
else
begin
ShowMessage('Client');
IdTcpClient1 := TIdTCPClient.Create(nil);
//IdTcpClient1.DefaultPort := StrToInt(Settings.SocketPortEdit.SelText);
end;
end;
答案 0 :(得分:1)
服务器期望每个消息正好接收1024个字节,不多也不少。客户端实际发送的是1024字节吗?我猜不是。 ReadBytes(1024)
在完全读取1024个字节之前不会退出,它不会读取更少的字节。如果您需要这种功能,请传递-1而不是1024. ReadBytes(-1)
将返回当时可用的任何字节。
答案 1 :(得分:0)
最后是工作代码。
procedure TSocket.IdTCPServer1Execute(AContext: TIdContext);
var
Socket_Receive_Buffer: TIdBytes;
Socket_Input_Length: integer;
Input_Buffer: TByteArray;
begin
with AContext.Connection do
begin
IOHandler.ReadBytes(Socket_Receive_Buffer, -1, false);
Socket_Input_Length := Length(Socket_Receive_Buffer);
if Socket_Input_Length > 0 then
begin
BytesToRaw(Socket_Receive_Buffer,Input_Buffer,Socket_Input_Length);
Terminal.GuiTerminalPutInput(Input_Buffer, Socket_Input_Length);
end;
end;
end;