Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sockets TCP套接字停止发送数据(Delphi)_Sockets_Delphi_Networking_Tcp - Fatal编程技术网

Sockets TCP套接字停止发送数据(Delphi)

Sockets TCP套接字停止发送数据(Delphi),sockets,delphi,networking,tcp,Sockets,Delphi,Networking,Tcp,我正在创建套接字连接,并使用一个线程使用以下代码通过套接字连续发送数据: if (FSocketSession.Connected) and (Msg.JSONEvent <> '') then begin FSocketSession.Send(TEncoding.UTF8.GetBytes(Msg.JSONEvent)) Msg.Free; end else begin FSocketSession.Co

我正在创建套接字连接,并使用一个线程使用以下代码通过套接字连续发送数据:

    if (FSocketSession.Connected) and (Msg.JSONEvent <> '') then
    begin
      FSocketSession.Send(TEncoding.UTF8.GetBytes(Msg.JSONEvent))
      Msg.Free;
    end
    else
    begin
      FSocketSession.Connect;
    end;

我注意到,在某些PC上,套接字在一段时间后(通常在1或2分钟后)停止发送数据,而在其他PC上,它运行时没有任何问题。有人在代码中看到可能导致这种情况发生的东西吗?如果需要,我可以提供更多信息。

我发现您的代码存在一些问题

如果
JSONEvent
为空,您将调用
Connect()
,即使
Connected
已为true,并且您将泄漏
Msg
对象。代码应该更像这样:

if FSocketSession.Connected then
begin
  if Msg.JSONEvent <> '' then
    FSocketSession.Send(TEncoding.UTF8.GetBytes(Msg.JSONEvent));
  Msg.Free;
end
else
begin
  FSocketSession.Connect;
end;
if FSocketSession.Connected then
begin
  if Msg.JSONEvent <> '' then
    FSocketSession.Send(TEncoding.UTF8.GetBytes(Msg.JSONEvent));
  Msg.Free;
end
else
begin
  FSocketSession.Connect;
end;
function TSocketSession.Send(const ADataToSend: TBytes): Integer;
const
  SleepTimeMS = 10;
var
  Stopwatch: TStopwatch;
  SentBytes, BytesToSend: Integer;
  PData: PByte;
begin
  SiMain.TrackMethod(Self, 'Send');
  {$IFDEF USE_SSL}
  if FIsSSL then
  begin
    SiMain.LogInteger('SslState', Ord(FSocket.SslState));
  end;
  {$ENDIF}
  FDataSent := False;
  if FSocket.State = wsConnected then
  begin
    PData := PByte(ADataToSend);
    BytesToSend := Length(ADataToSend);
    while BytesToSend > 0 do
    begin
      SentBytes := FSocket.Send(PData, BytesToSend);
      SiMain.LogInteger('SentBytes', SentBytes);
      if SentBytes <= 0 then
      begin
        // error handling ...
        Result := ...;
        Exit;
      end;
      Inc(PData, SentBytes);
      Dec(BytesToSend, SentBytes);
    end;
    Stopwatch := TStopwatch.StartNew;
  end;
  while (FSocket.State = wsConnected) and (not FDataSent) do
  begin
    FSocket.MessagePump;
    Sleep(SleepTimeMS);
    if (Stopwatch.ElapsedMilliseconds >= FTimeout) then
    begin
      FError := CErrorCommTimeout;
      break;
    end;
  end;

  Result := FError;
end;