问题描述
我正在使用带有 C++ 的 Windows 套接字。在接下来的调用中,我试图向刚刚连接的套接字回复一条消息。
我尝试在 C++ 中使用虚拟客户端进行连接。它会连接但 recv() 不会收到任何东西。
然后我尝试使用 telnet,它立即生效,就像我想要的那样。
SOCKET s = accept(ls,(sockaddr*)&clientSin,&s_len);
if (s == INVALID_SOCKET) {
cerr << "Error in accept call: " << WSAGetLastError();
}
else {
cout << "Connection accepted at,socket no. :" << s << endl;
//adding to list of incoming sockets
inactiveList.push_back(s);
//send message to client requesting credentials
char buff[10];
// the character 'x' is a code to the client to provide the server with the credentials
buff[0] = 'x';
buff[1] = '\0';
//send(s,buff,2,0);
if (send(s,"From Vic: ",10,0) == INVALID_SOCKET)
{
int errorcode = WSAGetLastError();
cerr << "send to client Failed: " << errorcode << endl;
closesocket(s);
continue;
}
Sleep(1000);
if (send(s,0) == INVALID_SOCKET)
{
int errorcode = WSAGetLastError();
cerr << "send to client Failed: " << errorcode << endl;
closesocket(s);
continue;
}
}
接收代码为:
tnb = 0;
while ((nb = recv(s,&buff[tnb],LInesZ - tnb,0)) > 0)
{
tnb += nb;
}
/* If there was an error on the read,report it. */
if (nb < 0)
{
printf("recv Failed: %d\n",WSAGetLastError());
return 1;
}
if (tnb == 0)
{
printf("disconnect on recv");
}
/* Make the response NULL terminated and display it. Using C output */
printf("tnb = %d\n",tnb);
buff[tnb] = '\0';
puts(buff);
解决方法
接受我所有的评论并将其转化为答案。
我怀疑您的 recv 循环一直在继续,因为您没有发送足够的数据使其脱离循环。
改变这个:
while ((nb = recv(s,&buff[tnb],LINESZ - tnb,0)) > 0)
{
tnb += nb;
}
为此:(请注意,我正在为数组 buff 分配 +1)
char buff[LINESZ+1]; // +1 for null terminator
buff[0] = '\0';
tnb = 0;
while (tnb < LINESZ)
{
nb = recv(s,LINESZ-tnb,0);
if (nb < 0)
{
printf("Error on socket: %d\n",(int)WSAGetLastError());
break;
}
else if (nb == 0)
{
printf("Remote socket closed\n");
break;
}
printf("Received: %d bytes\n",(int)nb);
tnb += nb;
buff[tnb] = '\0'; // null terminate the end of the buffer so it will print reliably
}