你刚刚给我修改的服务器端和客户端的代码后为什么服务器端不显示任何消息 服务器端代码 #define _WINSOCK_DEPRECATED_NO_WARNINGS#include <stdio.h>#include <Winsock2.h>#ifndef MSG_NOSIGNAL#define MSG_NOSIGNAL 0#endif#pragma comment(lib,"ws2_32.lib")int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { return 1; } if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return 1; } // 创建套接字并绑定到本地地址和端口 SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); int optval = 1; setsockopt(sockSrv, SOL_SOCKET, SO_REUSEADDR, (const char*)&optval, sizeof(optval)); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); // 监听连接请求并接受客户端连接 listen(sockSrv, 5); SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); SOCKET sockConn; fd_set fdReads; while (1) { // 使用 select() 函数实现非阻塞接收客户端连接 FD_ZERO(&fdReads); FD_SET(sockSrv, &fdReads); int ret = select(sockSrv + 1, &fdReads, NULL, NULL, NULL); if (ret < 0) { break; } if (FD_ISSET(sockSrv, &fdReads)) { sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len); char sendBuf[50]; printf(sendBuf, "Welcome %s to here!\n", inet_ntoa(addrClient.sin_addr)); send(sockConn, sendBuf, strlen(sendBuf) + 1, MSG_NOSIGNAL); } // 使用 select() 函数实现非阻塞接收客户端消息 FD_ZERO(&fdReads); FD_SET(sockConn, &fdReads); ret = select(sockConn + 1, &fdReads, NULL, NULL, NULL); if (ret < 0) { break; } if (FD_ISSET(sockConn, &fdReads)) { char recvBuf[50]; recv(sockConn, recvBuf, 50, 0); printf("Received from client: %s\n", recvBuf); // 将客户端发送的消息广播给所有连接的客户端 for (SOCKET i = 0; i < FD_SETSIZE; i++) { if (FD_ISSET(i, &fdReads)) { send(i, recvBuf, strlen(recvBuf) + 1, MSG_NOSIGNAL); } } } } closesocket(sockSrv); WSACleanup(); return 0;}
时间: 2024-03-05 19:50:54 浏览: 138
在服务器端代码中,当有新客户端连接时,你使用了一个未初始化的字符数组`sendBuf`来存储欢迎消息,这会导致 `printf()` 函数输出随机值。你需要先初始化 `sendBuf`,然后使用 `sprintf()` 函数将欢迎消息写入缓冲区。以下是修改后的代码:
```
// 使用 select() 函数实现非阻塞接收客户端连接
FD_ZERO(&fdReads);
FD_SET(sockSrv, &fdReads);
int ret = select(sockSrv + 1, &fdReads, NULL, NULL, NULL);
if (ret < 0) {
break;
}
if (FD_ISSET(sockSrv, &fdReads)) {
sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &len);
char sendBuf[50] = { 0 };
sprintf(sendBuf, "Welcome %s to here!\n", inet_ntoa(addrClient.sin_addr));
send(sockConn, sendBuf, strlen(sendBuf) + 1, MSG_NOSIGNAL);
}
// 使用 select() 函数实现非阻塞接收客户端消息
FD_ZERO(&fdReads);
FD_SET(sockConn, &fdReads);
ret = select(sockConn + 1, &fdReads, NULL, NULL, NULL);
if (ret < 0) {
break;
}
if (FD_ISSET(sockConn, &fdReads)) {
char recvBuf[50] = { 0 };
recv(sockConn, recvBuf, 50, 0);
printf("Received from client: %s\n", recvBuf);
// 将客户端发送的消息广播给所有连接的客户端
for (SOCKET i = 0; i < FD_SETSIZE; i++) {
if (FD_ISSET(i, &fdReads)) {
send(i, recvBuf, strlen(recvBuf) + 1, MSG_NOSIGNAL);
}
}
}
```
这样一来,当有新客户端连接时,服务器就可以正确地发送欢迎消息了。
阅读全文