我刚开始使用winsock2,并为服务器编写了以下代码,用于将字符串发送给在同一台计算机上运行的客户端(连接到127.0.0.1,与服务器设置侦听的端口相同)。
如果这重要的话,我正在使用MinGW。
我遇到的问题是,listen()似乎很早就完成了,但是返回了一个成功的代码。这是一个问题,因为当调用accept()时,它似乎永远阻塞。无论我是否运行客户端程序,都会发生此事件,而且我已经尝试过在前后运行客户端程序,但这似乎不会影响它。
// -1: "Could not initialize WSA."
// -2: "Could not create listener socket."
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <cstdio>
#define port 0x0ABC
UINT64 trStrLen (char* str)
{
if (str == NULL) return 0;
UINT64 pos = 0;
while (*(str + pos) != '\0') pos++;
return pos;
};
#include <cstdio>
int main ()
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,0),&wsadata)) return -1;
SOCKET server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
SOCKADDR_IN sin;
memset(&sin,0,sizeof(SOCKADDR_IN));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = INADDR_ANY;
int socksize = sizeof(SOCKADDR);
while (bind(server,(SOCKADDR*)(&sin),socksize) == SOCKET_ERROR) return -2;
char* TEMP_TO_SEND = "Billy Mays does not approve.";
UINT64 TEMP_SEND_LEN = trStrLen(TEMP_TO_SEND);
printf("Server online.\n");
while (true)
{
printf("Waiting for connections.\n");
while (listen(server,SOMAXCONN) == SOCKET_ERROR);
printf("Client requesting connection.\n");
SOCKET client = accept(server,NULL,NULL);
printf("Accept is no longer blocking.\n");
if (client != INVALID_SOCKET)
{
printf("Attempting to send information to the client...\n");
if (send(client,TEMP_TO_SEND,TEMP_SEND_LEN,0) == SOCKET_ERROR) printf("The information wasn't sent properly.\n");
else printf("The client received the information.\n");
}
else printf("Couldn't establish a connection to the client.\n");
};
};这可能是很明显的事情,但我没有看到,所以任何提示都会有帮助。
发布于 2013-10-06 06:38:20
listen()不是一个阻塞呼叫。它对电视网没有任何影响。它只是将套接字置于被动侦听模式,设置待办事项队列并返回。阻塞调用是accept():它阻塞直到一个传入连接完成,然后为它返回一个套接字。
因此,您不应该在一个listen()循环中调用while。
bind()也是如此。就打一次吧。
https://stackoverflow.com/questions/19205801
复制相似问题