gpt4 book ai didi

c - 本地 linux 套接字接收旧数据

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:52 24 4
gpt4 key购买 nike

我刚刚写了一个程序,使用本地套接字在两个进程之间进行通信

如果客户端向服务器发送一条消息,然后关闭连接,服务器只会收到一条消息

客户:

   send(srvfd,data,size,0)
close(srvfd)

服务器:

   n=recv(fd,buf,size,0)

但是,如果客户端发送一条消息,服务器也发送一条消息(任何字符串)给客户端,然后客户端关闭连接,服务器将收到客户端发送的旧消息

客户:

   send(srvfd,data,size,0)
n=recv(srvfd,buf,size,0)
close(srvfd)

服务器:

   n=recv(fd,buf,size,0)
send(fd,"response",8,0)
n=recv(fd,buf,size,0) //receive the first message again

这是我的初始化代码:

struct sockaddr_un srvAddr;
int listenFd = socket(PF_UNIX, SOCK_STREAM, 0);
if (listenFd < 0) {
perror("cannot create communication socket");
throw runtime_error("cannot create communication socket");
}
srvAddr.sun_family = AF_UNIX;
strncpy(srvAddr.sun_path, sockFile.c_str(), sockFile.size());
unlink(sockFile.c_str());

int ret = bind(listenFd, (struct sockaddr*) &srvAddr, sizeof(srvAddr));
if (ret == -1) {
perror("cannot bind server socket");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot bind server socket");
}

ret = listen(listenFd, BACKLOG);
if (ret < 0) {
perror("cannot listen the client connect request");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot listen the client connect request");
}

最佳答案

send(fd,"response",8,0)
n=recv(fd,buf,size,0) //receive the first message again

不,你没有。你得到的是 n == 0,意思是流结束。这也意味着零字节被传输到缓冲区中,因此现在缓冲区中的所有内容现在都没有意义。

不要忽略返回码。

关于c - 本地 linux 套接字接收旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32635326/

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