-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket_demo.c
116 lines (100 loc) · 2.59 KB
/
socket_demo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* File: main.c
* Author: starlight36
*
* Created on 2012年9月19日, 下午8:45
*/
#include <stdio.h> // for printf
#include <stdlib.h> // for exit
#include <string.h> // for bzero
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h> // for sockaddr_in
#include <sys/types.h> // for socket
#include <sys/socket.h> // for socket
#include <sys/stat.h>
#include <pthread.h>
#define SERVER_PORT 8090
#define LISTEN_QUEUE_LENGTH 20
#define BUFFER_SIZE 1024
#define MAX_THREAD_NUM 100
int thread_count = 0;
pthread_t threads[MAX_THREAD_NUM];
/**
* 接收数据的执行函数
* @param conn_socket
*/
void recv_data(int conn_socket);
/*
* 主方法
*/
int main(int argc, char** argv)
{
// 建立Socket
int server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
printf("Socket create failed.\n");
return EXIT_FAILURE;
}
{
int opt = 1;
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
}
// 设置服务器端监听套接字参数
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof (server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(SERVER_PORT);
// 绑定端口
if (bind(server_socket, (struct sockaddr*) &server_addr, sizeof (server_addr)))
{
printf("Bind port %d failed.\n", SERVER_PORT);
return EXIT_FAILURE;
}
// 开始监听
if (listen(server_socket, LISTEN_QUEUE_LENGTH))
{
printf("Server Listen Failed!");
return EXIT_FAILURE;
}
// 开始处理客户端连接
bzero(&threads, sizeof(pthread_t) * MAX_THREAD_NUM);
while (1)
{
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);
// 建立客户端连接
int client_conn = accept(server_socket, (struct sockaddr*) &client_addr, &length);
if (client_conn < 0)
{
printf("Server Accept Failed!\n");
return EXIT_FAILURE;
}
// 新建线程, 使用新线程与客户端交互
int pthread_err = pthread_create(threads + (thread_count++), NULL, (void *)recv_data, (void *)client_conn);
if (pthread_err != 0)
{
printf("Create thread Failed!\n");
return EXIT_FAILURE;
}
}
close(server_socket);
return (EXIT_SUCCESS);
}
void recv_data(int conn_socket)
{
char buffer[BUFFER_SIZE];
bzero(buffer, BUFFER_SIZE);
int length = 0;
while (length = recv(conn_socket, buffer, BUFFER_SIZE, MSG_WAITALL))
{
if (length < 0)
{
printf("Server Recieve Data Failed! code %d\n", length);
}
printf("%s", buffer);
bzero(buffer, BUFFER_SIZE);
}
close(conn_socket);
}