gpt4 book ai didi

c++ - 客户端和服务器无法交换数据,因为都得到 "stuck"

转载 作者:行者123 更新时间:2023-11-28 05:32:40 26 4
gpt4 key购买 nike

简介:

我研究了 blocking TCP server 的 MSDN 示例和 blocking TCP client .

鉴于修改这些示例以创建简单的聊天应用程序,我想尝试一些简单的事情。

首先,我尝试实现以下内容:

  • 从服务器发送消息
  • 在客户端接收并显示该消息
  • 发送客户端响应
  • 接收并显示客户端的响应

相关信息

我提前为冗长的代码道歉,但我坚信提交 SSCCE 与我相关对于客户端和服务器,为了让社区有机会解决问题。

我已尝试使代码尽可能少,但不想省略基本的错误检查。

您可以将两者复制/粘贴到单个 .cpp 文件中,它们应该可以毫无问题地编译和运行:

服务器代码:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

#pragma comment (lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void)
{
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;

struct addrinfo *result = NULL;
struct addrinfo hints;

int iResult;
char recvbuf[DEFAULT_BUFLEN] = "";
int recvbuflen = DEFAULT_BUFLEN;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}

// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}

// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}

// No longer need server socket,
// because I want to accept only 1 client
closesocket(ListenSocket);

// ===================== let us try to send a message...
std::string message = "Test message from server !!!";
int total = message.size();
const int messageLength = message.size();

while (iResult = send( ClientSocket,
// send only the missing part of the string, if send failed to deliver entire packet:
// we move the start of the string forward by messageLength - total
// while we send remaining number of bytes, which is held in total
message.substr(messageLength - total, total).c_str(), total, 0),
iResult > 0)
{
total -= iResult;
}

if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}

/* // adding this, seems to solve the problem ???
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
*/
// receive response from client...
while (iResult = recv(ClientSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}

if(iResult < 0)
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}

// cleanup
closesocket(ClientSocket);
WSACleanup();

getchar(); // so I can stop the console from immediately closing...
return 0;
}

客户端代码:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

#pragma comment (lib, "Ws2_32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;

char recvbuf[DEFAULT_BUFLEN] = "";
int iResult;
int recvbuflen = DEFAULT_BUFLEN;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}

// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
{
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}

// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET)
{
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}

// receive message from server...
while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}

if(iResult < 0)
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}

// ===================== let us try to send a message...
std::string message = "Client response...";
int total = message.size();
const int messageLength = message.size();

while (iResult = send( ConnectSocket,
// send only the missing part of the string, if send failed to deliver entire packet:
// we move the start of the string forward by messageLength - total
// while we send remaining number of bytes, which is held in total
message.substr(messageLength - total, total).c_str(), total, 0),
iResult > 0)
{
total -= iResult;
}

if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}

// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}

// cleanup
closesocket(ConnectSocket);
WSACleanup();

getchar(); // so I can stop the console from immediately closing...
return 0;
}

问题:

我已经实现了解决方案,但没有得到预期的结果。

服务器发送消息,客户端成功接收并显示它,但随后客户端无限卡住,而不是将其响应发送给服务器,这也无限地阻塞了服务器。

我为解决这个问题所做的努力:

第一次尝试:

使用调试器,我在客户端的接收 block 之后放置了断点,只是为了确定客户端在收到第一条消息后永远不会到达那里。

我相信 while 循环应该再次调用 recv,它应该返回 0,从而强制循环结束。

在我点击 Continue 后,调试器甚至没有继续显示客户端接收缓冲区的内容,而是表现出我目前无法描述的行为,因为我不是以英语为母语的人。

第二次尝试:

我也曾尝试使用 CreateThread 将服务器的接收循环放入线程中,但这也无济于事。

我也曾尝试将来自客户端的接收循环放入线程中,但也失败了。

我曾尝试将客户端和服务器接收循环放入线程中,但也失败了。

第三次尝试:

最后,我在服务器代码中添加了对shutdown(ClientSocket, SD_SEND)的调用,你会在代码的下半部分找到它,它被注释掉了。

这似乎解决了问题,但我不确定这是否是正确的解决方案,因为我刚刚开始使用 Winsock。

问题:

  • 如何绕过在 send 之后添加 shutdown 的“解决方案”?
  • 如果以上是唯一的方法,我应该在 recv 之后做同样的事情吗?我应该发送什么参数(SD_SENDSD_RECEIVESD_BOTH) ?

再次为冗长的帖子道歉,但作为新手,我已尝试提供尽可能多的信息以使您的任务更轻松。

最佳答案

在简要浏览了您的代码后,我敢猜测客户端中的以下代码块:

while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}

实际上是你的问题。您提到关闭服务器端的套接字可以解决问题。对于套接字,只要套接字处于事件状态或直到数据通过,recv 调用就会阻塞,但是当套接字关闭时,您将获得 0 的 recv。

如果你只想接收一个消息,而不是在recv上循环,你应该在处理完第一个recv后循环回recv调用,或者你应该在套接字上轮询以查看是否有实际上数据首先可用。

关于c++ - 客户端和服务器无法交换数据,因为都得到 "stuck",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081848/

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