我正在开发一个相当简单的客户端/服务器应用程序,并且在使用winsock API 提供的recv从客户端接收 TStringStream 时遇到了一些麻烦。
我不断收到此错误:“0x00000000 处的访问冲突:读取地址 0x00000000”。
客户端仅将文本复制到 TStringStream 中,获取它的长度并将其发送到服务器。然后服务器接收 Stream 并输出它的文本。下面是一些抽象代码摘录。
{ the server's part }
inBuf := TStringStream.Create;
{ MAKE THIS SOCKET A PASSIVE ONE }
listen(serversock, LISTENQ);
{ ACCEPT CONNECTION ON serversock FROM cliaddr -> CONNECTED SOCKET = connfd }
connfd := accept(serversock, @cliaddr, @len);
recv(connfd, inLen, sizeof(inLen), 0);
//up to here everything is fine with the strem:
//Size = InLen, Position = 0, all bytes are '0'
rec := recv(connfd, inBuf, inLen, 0);
//rec = inLen, which is fine
//now this: inBuf: FMemory $1, FSize 9 (no matter how long the msg is)
// FPosition 7077987 and FBytes: many many random
DebugOutput(inBuf.DataString); //the error is thrown here
其中 connfd 是连接的套接字,servsock 是监听套接字,inLen 是包含 inBuf 长度的基数,inBuf 是全局 TStringStream。rec 是一个基数,包含 recv 接收到的字节数。
{ the client's send function }
function SSend(sock :TSocket; addr :sockaddr_in; msg :TStringStream) :Integer;
var
len: Cardinal;
begin
len := msg.Size;
send(sock, len, sizeof(len), 0);
msg.Seek(0,0);
send(sock, msg, sizeof(msg), 0);
Result := 0;
end;
以及客户对 SSend 的调用:
{ CREATE (OUTPUT)STREAM }
s := TStringStream.Create;
s.WriteString(_input.Text);
//_input is a TMemo with text, let's say, ´hello´
SSend(client, servaddr, s);
//client is a TSocket
提前感谢您的帮助!
p1.e