在程程序中为了控制超时使用了TWinSocketStream 对象来读取socket中的数据,socket是阻塞方式。
调用如下
     csSocket.Active:=true;
     csSocket.Socket.SendText('i want passwd');
     RecvStr:=SocketRead(csSocket,5000);
     csSocket.Active:=false;
SocketRead读出的串为空,但不是由于超时返回的。
如果用 csSocket.Socket.receivebuf 读取可以读到我想要的内容,但是这样就无法
设置超时。
SocketRead读出的串为空,这种情况我试验了几台机器有的机器可以读出,有的就是返回空串。
//////////////SocketRead
Function SocketRead(ClientSocket : TClientSocket; timeout: integer): string;
var
  Stream : TWinSocketStream;
  Buffer : array[0 .. 2048] of Char;
  Packet_len : Integer;
  i : Integer;
begin
  Result := '';
  { make sure connection is active }
  if ClientSocket.Socket.Connected then
  begin
    Stream := TWinSocketStream.Create(ClientSocket.Socket, timeout);
    try
      FillChar(Buffer, 2048, 0); { initialize the buffer }      if Stream.WaitForData(timeout) then
      begin
        Packet_len := Stream.Read(Buffer, 2048);
        if  Packet_len > 0 then
        begin
          for i:=0 to Packet_len-1 do
          begin
            if Buffer[i] = Chr(0) then
              Buffer[i] := ' ';
          end;
          Result := Buffer;
        end
        else
          Result := '';
      end
      else
      begin
        Result := '';
      end;
    finally
      Stream.Free;
    end;
  end;
end;