【发布时间】:2014-06-02 11:36:33
【问题描述】:
我正在尝试使用 Beej 的套接字指南中的代码在 Linux 中实现 C 套接字服务器,该指南位于此处:
http://beej.us/guide/bgnet/examples/server.c
这行得通,我已经用 C# 编写了一个 Windows 客户端来与它通信。一旦客户端连接,我让它向服务器发送一个字节数组,服务器读取它,然后发回一个字节数组。这行得通。
但是,在此之后,如果我让客户端尝试发送另一个字节数组,我会收到一个 Windows 弹出窗口,提示“已建立的连接已被主机中的软件中止。”然后我必须再次与客户端重新连接。我想无限期地保持连接打开,直到客户端发送断开连接命令,但是尽管阅读了 Beej 的指南,但我似乎没有得到它。目前我什至没有尝试实现断开连接命令,我只是尝试保持连接打开,直到我关闭服务器。
我已经尝试删除 Beej 代码中的 close() 调用:
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
ProcessRequest(new_fd); // this is not Beej's code, I've replaced his code here (which was a simple string send()) with a function call that does a read() call, processes some data, then sends back a byte array to the client using send().
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
但这只是让我陷入“套接字接受:错误的文件描述符”的无限循环(我尝试同时删除 close(new_fd) 行和同时删除行,以及 close(sockfd) 行。 任何更精通 C 套接字编程的人都可以给我一个提示我应该在哪里寻找吗?谢谢。
【问题讨论】:
-
您确定服务器已断开连接吗?我不确定从客户端抛出的消息是否表明对等关闭。 Wireshark 捕获应该可以确认这一点。