在Linux系统中,Socket是一种网络通信机制,允许不同计算机上的进程通过网络进行数据交换。多线程(Multithreading)是指在一个程序中同时运行多个线程,每个线程执行不同的任务,从而提高程序的并发性和效率。
以下是一个简单的Linux下使用Socket和多线程的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#define PORT 8080
#define MAX_CLIENTS 10
void *handle_client(void *arg);
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
pthread_t threads[MAX_CLIENTS];
int thread_count = 0;
// 创建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定socket
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Server is listening on port %d\n", PORT);
while (1) {
// 接受新连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("New connection, socket fd is %d, ip is : %s, port : %d\n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port));
// 创建新线程处理客户端请求
if (thread_count < MAX_CLIENTS) {
if (pthread_create(&threads[thread_count], NULL, handle_client, (void*)&new_socket) != 0) {
perror("pthread_create");
close(new_socket);
} else {
thread_count++;
}
} else {
printf("Max clients reached, closing connection\n");
close(new_socket);
}
}
return 0;
}
void *handle_client(void *arg) {
int new_socket = *(int*)arg;
char buffer[1024] = {0};
int valread;
while (1) {
valread = read(new_socket, buffer, 1024);
if (valread <= 0) {
printf("Client disconnected\n");
break;
}
printf("Received message: %s\n", buffer);
send(new_socket, buffer, strlen(buffer), 0); // Echo back
memset(buffer, 0, sizeof(buffer));
}
close(new_socket);
pthread_exit(NULL);
}
通过以上方法,可以有效解决Linux下Socket多线程编程中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云