qfedu-network-advanced-level/day3/tcp_s1.c

87 lines
2.2 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// tcp_c1 的服务端
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h> // bzero
#include <stdlib.h> // atoi
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("usage: %s port\n", argv[0]);
return 1;
}
// TCP 的 socket 套接字类型 SOCK_STREAM
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0)
{
perror("socket");
return 1;
}
// 设置绑定绑定服务器的IP和端口号
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
// 创建监听队列
if (listen(sock_fd, 50) == -1)
{
perror("listen");
}
// 接收客户端的连接
struct sockaddr_in client_addr;
bzero(&client_addr, sizeof(client_addr));
socklen_t client_addr_len = sizeof(client_addr);
// 阻塞到有客户端连接为止
int client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len);
// 客户端 ip
char client_ip[16] = "";
inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_ip, 16);
printf("%s(%d) 连接成功\n", client_ip, ntohs(client_addr.sin_port));
while (1)
{
// 接受(读取客户端数据)
char buf[128] = "";
ssize_t recv_len = read(client_fd, buf, 128); // 用 recv 也可以
// ssize_t recv_len = recv(client_fd, buf, 128, 0);
if (recv_len > 0)
{
printf("%s say: %s\n", client_ip, buf);
}
if (strncmp(buf, "bye", 3) == 0)
{
break;
}
memset(buf, 0, 128);
scanf("%s", buf);
// if (send(client_fd, buf, strlen(buf) + 1, 0) != -1) // 用 send 也可以
if (write(client_fd, buf, strlen(buf) + 1) != -1) // 用 send 也可以
{
printf("发送数据 OK\n");
}
}
close(client_fd);
close(sock_fd);
printf("----over----\n");
return 0;
}