[英]local linux socket receives old data
我剛剛編寫了一個使用本地套接字在兩個進程之間進行通信的程序
如果客戶端向服務器發送一條消息,然后關閉連接,則服務器將僅收到一條消息
克朗特:
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
,這意味着流結束。 這也意味着將零字節傳輸到緩沖區中,因此緩沖區中的所有內容現在都沒有意義。
不要忽略返回碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.