我正试图进入网络编程,并一直在遵循一个关于套接字的指南。我用C写了一个简单的Windows TCP服务器和客户端,但似乎无法让它们工作。当客户端连接时,服务器抛出一个“Bad file descriptor”错误并关闭。我不明白刚刚由accept()
创建的文件描述符怎么会是坏的。我对此做过研究,只找到了在阅读之前关闭文件的人,而我没有。
下面是代码:
服务器
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
int main(int argc, char *argv[])
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
SOCKET sock, newsock;
int portno, clilen;
char buffer[256];
SOCKADDR_IN serv_addr, cli_addr;
int n;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("Error opening socket");
exit(1);
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
portno = 5001;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sock, (SOCKADDR *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("Eror on binding");
exit(1);
}
listen(sock, 5);
clilen = sizeof(cli_addr);
newsock = accept(sock, (SOCKADDR *) &cli_addr, &clilen);
if (newsock < 0)
{
perror("Error on accept");
exit(1);
}
memset(buffer, 0, 256);
n = read(newsock, buffer, 255);
if (n < 0)
{
perror("Error reading from socket");
exit(1);
}
printf("Here is the message : %s\n", buffer);
n = write(newsock, "I got your message", 18);
if (n < 0)
{
perror("Error writing to socket");
exit(1);
}
WSACleanup();
return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
int main(int argc, char *argv[])
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
SOCKET sock;
int portno, n;
SOCKADDR_IN serv_addr;
HOSTENT *server;
char buffer[256];
if (argc < 3)
{
fprintf(stderr, "Usage : %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("Error opening socket\n");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL)
{
perror("Error, no such host");
exit(1);
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *) &serv_addr.sin_addr.s_addr, (char *) server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sock, (SOCKADDR *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("Error connecting to server");
exit(1);
}
printf("Please enter your message : ");
memset(buffer, 0, 256);
fgets(buffer, 255, stdin);
n = write(sock, buffer, strlen(buffer));
if (n < 0)
{
perror("Error writing to socket");
exit(1);
}
memset(buffer, 0, 256);
n = read(sock, buffer, 255);
if (n < 0)
{
perror("Error reading from socket");
exit(1);
}
printf("%s\n", buffer);
WSACleanup();
return 0;
}
...以下是输出以防万一:
C:\...myfolder>server
*here it does nothing until I start the client with "client 127.0.0.1 5001" in another window*
Error reading from socket: Bad file descriptor
你看到我的代码有什么问题了吗?提前感谢您的帮助!
1条答案
按热度按时间ttp71kqs1#
我会把它放在注解中,但请尝试使用recv()函数而不是read()。这是因为read()不调用Socket API,所以就Windows而言,文件描述符无效。
同样,在客户端中,您应该使用send()而不是write()。