C++ c++;插座recv功能回路
我正在尝试通过tcp套接字背靠背发送和接收2个数据。协议写在下面C++ c++;插座recv功能回路,c++,sockets,C++,Sockets,我正在尝试通过tcp套接字背靠背发送和接收2个数据。协议写在下面 客户端发送数据 在服务器上接收数据并将其发送回客户端时 现在使用下面的客户端代码,我无法获得第二个数据,我认为“Recv”函数有问题。下面是代码片段 int Recv(char* buffer, int size) { int total = 0, n = 0; while((n = ::recv(m_hSocket, buffer+total, size-total-1, 0)) > 0) { to
int Recv(char* buffer, int size)
{
int total = 0, n = 0;
while((n = ::recv(m_hSocket, buffer+total, size-total-1, 0)) > 0)
{
total += n;
}
buffer[total] = 0;
return total;
}
int SendAndReceiveData()
{
//CStringA cstData :: this data getting filled by some other code. Ignore!
//Send data
char chSendBuff[256];
memset(chSendBuff, 0, sizeof(chSendBuff));
sprintf_s(chSendBuff, sizeof(chSendBuff), "%s", (LPCTSTR)cstData);
send(m_hSocket, chSendBuff, (int)strlen(chSendBuff), 0);
//Read response
char chRecvBuff[256];
memset(chRecvBuff, 0, sizeof(chRecvBuff));
int iRet = Recv(chRecvBuff, 256);
}
您的接收函数应如下所示:
int receive(int sockfd, void *buf, size_t len, int flags)
{
size_t toread = len;
char *bufptr = (char*) buf;
while (toread > 0)
{
ssize_t rsz = recv(sockfd, bufptr, toread, flags);
if (rsz <= 0)
return rsz; /* Error or other end closed connection */
toread -= rsz; /* Read less next time */
bufptr += rsz; /* Next buffer position to read into */
}
return len;
}
int接收(int sockfd、void*buf、size\u t len、int标志)
{
尺寸=长度;
char*bufptr=(char*)buf;
而(探路者>0)
{
ssize_t rsz=recv(sockfd、bufptr、toread、flags);
如果(rsz)您可以使用char chSendBuff[256]={};
将数组归零。您不需要将接收到的缓冲区归零-这是浪费时间,因为您无论如何都要覆盖该缓冲区。“Recv”在收到256字节或连接关闭之前不会返回。您是否每次都发送256字节?如果不是,客户端是否在发送较少字节后关闭连接?also,'memset(chSendBuff,0,sizeof(chSendBuff));':cargo cult。你正在加载缓冲区,下一行是sprintf_s(),保证以null结尾的字符串。@MaximeGroushkin是的。不幸的是,网上有几个客户端/服务器示例使用这种垃圾,开发者几十年来一直在盲目复制memset/bzero,(通常会忽略recv返回的结果)。