Linux socket 搭建TCP服务器(C语言)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define MAX_BUF_SIZE 1024
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[MAX_BUF_SIZE];
int bytes_read;
// 创建socket文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
fprintf(stderr, "Socket creation failed\n");
exit(EXIT_FAILURE);
}
// 定义服务器端地址
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;
// 绑定socket到地址
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
fprintf(stderr, "Bind failed\n");
exit(EXIT_FAILURE);
}
// 监听socket
if (listen(server_fd, 3) < 0) {
fprintf(stderr, "Listen failed\n");
exit(EXIT_FAILURE);
}
// 接受客户端连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
fprintf(stderr, "Accept failed\n");
exit(EXIT_FAILURE);
}
printf("Server established\n");
// 接收客户端消息
while ((bytes_read = recv(new_socket, buffer, MAX_BUF_SIZE, 0)) > 0) {
buffer[bytes_read] = '\0';
printf("Received message: %s\n", buffer);
}
if (bytes_read == 0) {
printf("Client closed connection\n");
} else {
fprintf(stderr, "Recv failed\n");
}
// 关闭socket
close(new_socket);
close(server_fd);
return 0;
}
这段代码创建了一个基本的TCP服务器,并展示了如何接收客户端连接、接收消息和关闭连接。它是学习网络编程和了解TCP套接字编程的一个很好的起点。
评论已关闭