我正尝试使用Linux中的C网络编程读取和写入套接字。我分别在客户端和服务器程序中成功调用“写入”和“读取”。使用读取和写入功能的C中的套接字错误
我很难理解的部分是,在我的客户端程序中,我在服务器上循环并调用write 5次不同的时间,我循环并调用read 5次不同的次数。
这是预期的输出:
MSG: I got your message MSG: I got your message MSG: I got your message MSG: I got your message MSG: I got your message
这是实际的输出:
MSG: I got your messageI got your messageMSG: I got your messageI got your messageMSG: I got your messageMSG: MSG:
正如你所看到的预期输出和实际输出是不同的。看起来客户端能够在实际发送之前调用“写入”两次。
这是我的客户端代码
for(int i=0;i<5;i++)
{
int n = write(ssocket.socketFileDescriptor,"I got your message",18);
cout<<n<<" number of bytes written."<<endl;
if (n < 0) socketError("ERROR writing to socket");
}
这是服务器代码:
void* run(void* arg)
{
ServerSocket* ss = (ServerSocket*)arg;
//while(true)
for(int i=0;i<5;i++)
{
char buffer[256];
bzero(buffer,256);
int n = read(ss->newsockfd,buffer,256);
printf("MSG: %s",buffer);
}
close(ss->newsockfd);
}
这是除了问题,下面这是过时的,在这一点上。
我缺少一个调用刷新或什么的?
Simulate Java's Thread class in C++
您假定TCP可以传输大于一个字节的消息。它不能 - 它是一个字节/八位字节的STREAMING协议,并且不知道一个字节之上的消息边界。如果您想传输更大,更复杂的消息,则需要TCP上的协议。这个问题有无数次 - 这么多,我不能看着:) – 2014-08-29 21:08:54
如果你使用的TCP套接字,然后发送的所有内容连接成一个流,当它被读取时,你会得到什么是可用的直到缓冲区大小)。您需要插入自己的消息边界并在接收器中解析流。 – molbdnilo 2014-08-29 21:12:04
所以我打开wireshark并确认每个'写'调用实际上创建了它自己的数据包。 所以这意味着阅读是双倍的。这是我看到'读',我说在我的代码中读取256个字节。 – Matthew 2014-08-30 19:56:18