gpt4 book ai didi

delphi - 使用(winsock 的)recv 接收时 TStringStream 被损坏?

转载 作者:行者123 更新时间:2023-12-03 15:09:14 26 4
gpt4 key购买 nike

我正在开发一个相当简单的客户端/服务器应用程序,但在使用 Winsock API 提供的 recv 从客户端接收 TStringStream 时遇到一些问题。
我不断收到此错误:“0x00000000 处的访问冲突:读取地址 0x00000000”。
客户端仅将文本复制到 TStringStream 中,获取其长度并将其发送到服务器。然后服务器接收流并输出它的文本。下面是一些抽象代码摘录。

{ 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

最佳答案

您正在向 recv 传递一个指向 TStringStream 对象本身的指针,而不是其数据缓冲区的指针。这就是对象被损坏的原因。使用 Memory 属性:recv(connfd, inBuf.Memory^, inLen, 0)

发送也是如此:从流发送数据,而不是流对象(SSend 中的 sizeof(msg) 仅返回指针的大小)。

关于delphi - 使用(winsock 的)recv 接收时 TStringStream 被损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com