// 创建用于通信的端点,并返回引用该端点的文件描述符
int socket(int domain, int type, int protocol);
// 将建立套接字返回的文件描述符与IP,端口绑定
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
// 将文件描述符引用的套接字标记为被动套接字,监听连接请求
int listen(int sockfd, int backlog);
// 接收对socket的连接
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
// 将网络字节序转为转本地IP (int -> 字符串)
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
// 将本地IP转网络字节序 (字符串 -> int)
int inet_pton(int af, const char *src, void *dst);
// 将 unsigned int 主机字节顺寻转为网络字节顺序
uint32_t htonl(uint32_t hostlong);
// 将 unsigned short int 主机字节顺寻转为网络字节顺序
uint16_t htons(uint16_t hostshort);
// 将 unsigned int 网络字节顺序转为主机字节顺序
uint32_t ntohl(uint32_t netlong);
// 将 unsigned short int 网络字节顺序转为主机字节顺序
uint16_t ntohs(uint16_t netshort);
/**
* @brief 半关闭 关闭服务器或客服端其中一方的文件描述符的某些权限
* @param sockfd 要关闭的一方对应的文件描述符
* @param how
* SHUT_RD 0 读
* SHUT_WR 1 写
* SHUT_RDWR 2 读写
*/
int shutdown(int sockfd, int how);
struct sockaddr_in
{
// 地址族
sa_family_t sin_family;
// 16位 TCP/UDP 端口号
uint16_t sin_port;
// 32位IP地址
struct in_addr sin_addr;
// 不使用
char sin_zero[8];
};
struct in_addr
{
// 32位 IPv4 地址
In_addr_t s_addr;
};
struct sockaddr
{
sa_family_t sa_family;
char sa_data[14];
}
下面分别是服务器端和客户端的源码,分别编译后,首先运行服务器端,然后运行客户端. 成功建立TCP连接后,服务器端显示客户端的IP和端口号. 客户端输入要发送的文本信息,服务器端收到后会显示出来,同时向客户端发送一条消息.
/**
* @name server.c
* @author IYATT-yx
* @brief 套接字TCP通信 - 服务器端
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
int main(void)
{
// 创建要监听的套接字
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd == -1)
{
perror("socket error");
return -1;
}
// 绑定listen_fd 和 本地所有IP,端口(11111)
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(11111);
server.sin_addr.s_addr = htonl(INADDR_ANY);
// 设置端口复用
int flag = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
int ret = bind(listen_fd, (struct sockaddr *)&server, sizeof(server));
if (ret == -1)
{
perror("bind error");
return -1;
}
// 设置监听
ret = listen(listen_fd, 20);
if (ret == -1)
{
perror("listen error");
return -1;
}
printf("服务器启动监听...\n");
// 等待并接收连接请求
struct sockaddr_in client;
socklen_t len = sizeof(client);
int client_fd = accept(listen_fd, (struct sockaddr *)&client, &len);
if (client_fd == -1)
{
perror("accept error");
return -1;
}
char ipbuf[64] = {0};
printf("请求连接的客户端IP: %s, 端口: %d\n",
inet_ntop(AF_INET, &client.sin_addr.s_addr, ipbuf,
sizeof(ipbuf)), ntohs(client.sin_port));
// 保持通信
while (true)
{
// 接收数据
char buf[1024] = {0};
ssize_t length = read(client_fd, buf, sizeof(buf));
if (length == -1)
{
perror("read error");
break;
}
else if (length == 0)
{
printf("客户端断开了连接!\n");
close(client_fd);
break;
}
else
{
// 显示收到的消息
printf("收到消息为: %s\n", buf);
memset(buf, 0, sizeof(buf));
strcpy(buf, "我是服务器");
// 回复信息
write(client_fd, buf, strlen(buf));
}
}
close(listen_fd);
close(client_fd);
}
/**
* @name client.c
* @author IYATT-yx
* @brief 套接字TCP通信 - 客户端
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
int main(void)
{
// 创建套接字
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
perror("socket error");
return -1;
}
// 连接服务器 127.0.0.1:11111
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(11111);
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr.s_addr);
connect(fd, (struct sockaddr *)&server, sizeof(server));
// 通信
while (true)
{
// 发送数据
char buf[1024];
memset(buf, 0, sizeof(buf));
printf("\n请输入要发送的信息:");
fgets(buf, sizeof(buf), stdin);
write(fd, buf, sizeof(buf));
// 等待接收数据
memset(buf, 0, sizeof(buf));
ssize_t len = read(fd, buf, sizeof(buf));
if (len == -1)
{
perror("read error");
return -1;
}
else if (len == 0)
{
printf("服务器断开了连接\n");
close(fd);
return -1;
}
else
{
printf("收到来自服务器的消息: %s\n", buf);
}
}
close(fd);
}
下面两个源码分别是利用 多进程 和 多线程 实现的简单并发服务器 (配合上面的客户端使用), 支持同时多个客户端连接
/**
* @name server.c
* @author IYATT-yx
* @brief 多进程并发服务器
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
// 子进程回收
void recycle(int num)
{
(void)num;
while (waitpid(-1, NULL, WNOHANG) > 0)
{
printf("回收子进程成功\n");
}
}
int main(void)
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd == -1)
{
perror("socket error");
exit(EXIT_FAILURE);
}
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
// 监听端口 11111
server.sin_port = htons(11111);
// 设置端口复用
int flag = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
// 绑定
if (bind(lfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
perror("bind error");
exit(EXIT_FAILURE);
}
// 最大监听20个
if (listen(lfd, 20) == -1)
{
perror("listen error");
exit(EXIT_FAILURE);
}
printf("服务器启动监听...\n");
// 信号回收子进程
struct sigaction act;
act.sa_handler = recycle;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGCHLD, &act, NULL);
struct sockaddr_in client;
socklen_t len = sizeof(client);
while (true)
{
// 父进程接收连接请求
int cfd = accept(lfd, (struct sockaddr *)&client, &len);
if (cfd == -1 && errno == EINTR)
{
cfd = accept(lfd, (struct sockaddr *)&client, &len);
}
else if (cfd == -1)
{
perror("accept error");
exit(EXIT_FAILURE);
}
char ipbuf[64] = {0};
uint16_t port = ntohs(client.sin_port);
printf("请求连接的客户端IP: %s, 端口: %d\n",
inet_ntop(AF_INET, &client.sin_addr.s_addr, ipbuf,
sizeof(ipbuf)), port);
// 创建子进程
pid_t pid = fork();
if (pid == 0)
{
close(lfd);
// 子进程, 通信
while (true)
{
char buf[1024];
memset(buf, 0, sizeof(buf));
ssize_t length = read(cfd, buf, sizeof(buf));
if (length == -1)
{
perror("read error");
exit(EXIT_FAILURE);
}
else if (length == 0)
{
printf("客户端%s:%d断开了连接!\n", ipbuf, port);
close(cfd);
exit(EXIT_SUCCESS);
}
else
{
printf("来自%s:%d的数据为: %s", ipbuf, port, buf);
// 返回数据
memset(buf, 0, sizeof(buf));
strcpy(buf, "服务器成功收到数据");
write(cfd, buf, strlen(buf));
continue;
}
return EXIT_SUCCESS;
}
}
else if (pid > 0)
{
close(cfd);
}
}
close(lfd);
}
/**
* @name server.c
* @author IYATT-yx
* @brief 多线程并发服务器
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
// 用于向子线程传数据的结构体
struct SockInfo
{
int fd;
struct sockaddr_in addr;
pthread_t id;
};
typedef struct SockInfo SockInfo;
void *com(void *arg)
{
SockInfo *info = (SockInfo *)arg;
char ipbuf[64] = {0};
char buf[1024] = {0};
inet_ntop(AF_INET, &info->addr.sin_addr.s_addr, ipbuf, sizeof(ipbuf));
uint16_t port = ntohs(info->addr.sin_port);
printf("请求连接的客户端IP: %s, 端口: %d\n", ipbuf, port);
while (true)
{
memset(buf, 0, sizeof(buf));
ssize_t len = read(info->fd, buf, sizeof(buf));
if (len == -1)
{
perror("read error");
close(info->fd);
info->fd = -1;
pthread_exit(NULL);
}
else if (len == 0)
{
printf("客户端%s:%d已断开了连接\n", ipbuf, port);
close(info->fd);
info->fd = -1;
pthread_exit(NULL);
}
else
{
printf("来自%s:%d的消息: %s", ipbuf, port, buf);
memset(buf, 0, sizeof(buf));
strcpy(buf, "服务器已收到数据");
write(info->fd, buf, strlen(buf));
}
}
return NULL;
}
int main(void)
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd == -1)
{
perror("socket error");
exit(EXIT_FAILURE);
}
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(11111);
int flag = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
if (bind(lfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
perror("bind error");
exit(EXIT_FAILURE);
}
if (listen(lfd, 20) == -1)
{
perror("listen");
exit(EXIT_FAILURE);
}
printf("服务器启动监听...\n");
socklen_t len = sizeof(struct sockaddr_in);
SockInfo info[20];
int i = 0;
for (i = 0; i < 20; ++i)
{
info[i].fd = -1;
}
while (true)
{
for (i = 0; i < 20; ++i)
{
if (info[i].fd == -1)
{
break;
}
}
if (i == 20)
{
printf("已超出设定的最大连接数\n");
break;
}
info[i].fd = accept(lfd, (struct sockaddr *)&info[i].addr, &len);
if (info[i].fd == -1)
{
perror("accept error");
exit(EXIT_FAILURE);
}
// 创建线程用于通信
pthread_create(&info[i].id, NULL, com, &info[i]);
// 线程分离
pthread_detach(info[i].id);
}
close(lfd);
// 只退出子线程
pthread_exit(NULL);
}