我刚刚开始学习用 C 语言进行网络编程。我做了一些测试,但遇到了一个错误。
我有一个客户:
客户端.c
#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
int main(void)
{
struct addrinfo hints, *res;
int sock;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("localhost", "5996", &hints, &res);
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
connect(sock, res->ai_addr, res->ai_addrlen);
char data[64];
int len = 13;
int br = recv(sock, data, len, 0);
printf("%s\n%s\n%d\n", strerror(errno), data, br);
return 0;
}
和服务器:
服务器.c
#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MYPORT "5996"
#define BACKLOG 10
int main(void)
{
struct sockaddr_storage their_addr;
socklen_t addr_size;
struct addrinfo hints, *res;
int sockfd, new_fd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, MYPORT, &hints, &res);
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bind(sockfd, res->ai_addr, res->ai_addrlen);
listen(sockfd, BACKLOG);
addr_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);
char *msg = "Hello World!!";
int len = strlen(msg);
int bs = send(new_fd, msg, len, 0);
close(sockfd);
}
当我启动服务器时,它等待连接,如果我启动客户端,我会收到消息“Hello World!!”,但是,一分钟左右,如果我尝试运行服务器然后运行客户端再次,我从strerror()调用中收到消息“传输端点未连接” 。
我确实阅读了有关此的其他问题,但问题是数据应该发送到从accept()调用返回的套接字......但我认为这就是我正在做的事情。我究竟做错了什么??...我知道这很愚蠢,但我是一个真正的初学者。