100万并发连接服务器
来源:互联网 发布:百度大圣卡 知乎 编辑:程序博客网 时间:2024/05/01 14:51
100万并发连接服务器笔记之准备篇
前言
测试一个非常简单服务器如何达到100万(1M=1024K连接)的并发连接,并且这些连接一旦连接上服务器,就不会断开,一直连着。
环境受限,没有服务器,刚开始都是在自己的DELL笔记本上测试,凭借16G内存,和优秀的vmware workstation虚拟机配合,另外还得外借别人虚拟机使用,最终还得搭上两台2G内存的台式机(安装centos),最终才完成1M并发连接任务。
- 测试程序也很简陋,一个C语言所写服务器程序,没有任何业务存在,收到请求后发送一些头部,不断开连接
- 测试端程序也是使用C语言所写,发送请求,然后等待接收数据,仅此而已
- 服务器端/测试端内存都受限(8G不够使用),要想完成1024K的目标,需要放弃一些东西,诸如业务不是那么完整
- 一台分配10G内存Centos服务器,两台分配6G内存Centos测试端,两台2G内存Centos测试端
- 假如热心的您可以提供丰富的服务器资源,那就再好不过了。
- 理论上200万的并发连接(IO密集型),加上业务,40G-50G的内存大概能够保证
说明
以前也做过类似的工作,量不大,没记录下来,一些压力测试和调优,随着时间流逝,早已忘记。这次是从零开始,基本上所有过程都会记录,一步一步,每一步都会遇到问题,并且给出相关解决问题的方法,最终完成目标。
为了方便,服务器端程序和客户端测试程序,都是使用C语言,不用像JAVA一样需要预先指定内存,感觉麻烦。使用较为原始的语言来写,可以避免不必要的调优工作。这中间,可能会穿插Java代码的思考方式。
可能需要懂点Linux,C,Java,假如您有更好的做法,或者建议,请直接告知,谢谢。
Linux系统
测试端和服务器端都选用较为熟悉的64位Centos 6.4,32位系统最多支持4G内存,太受限。IO密集型应用,对CPU要求不是很高。另外服务器确保安装上gcc,那就可以开工了。
所有端系统一旦安装完之后,默认不做任何设置。
服务器端程序
服务器端程序依赖libev框架,需要提前编译,然后存放到相应位置。下面是具体服务器端代码:
点击(此处)折叠或打开
- #include <arpa/inet.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <err.h>
-
- #include <unistd.h>
-
- #include "../include/ev.h"
-
- #define HTMLFILE_RESPONSE_HEADER \
- "HTTP/1.1 200 OK\r\n" \
- "Connection: keep-alive\r\n" \
- "Content-Type: text/html; charset=utf-8\r\n" \
- "Transfer-Encoding: chunked\r\n" \
- "\r\n"
- #define HTMLFILE_RESPONSE_FIRST \
- "div\">
点击(此处)折叠或打开
- static int server_port = 8000;
-
- struct ev_loop *loop;
- typedef struct {
- int fd;
- ev_io ev_read;
- } client_t;
-
- ev_io ev_accept;
-
- static int usr_num;
- static void incr_usr_num() {
- usr_num ++;
- printf("online user %d\n", usr_num);
- }
-
- static void dec_usr_num() {
- usr_num --;
-
- printf("~online user %d\n", usr_num);
- }
-
- static void free_res(struct ev_loop *loop, ev_io *ws);
-
- int setnonblock(int fd) {
- int flags = fcntl(fd, F_GETFL);
- if (flags < 0)
- return flags;
-
- flags |= O_NONBLOCK;
- if (fcntl(fd, F_SETFL, flags) < 0)
- return -1;
-
- return 0;
- }
-
- static int format_message(const char *ori_message, char *target_message) {
- return sprintf(target_message, "%X\r\n\r\n", ((int)strlen(ori_message) + 23), ori_message);
- }
-
- static void write_ori(client_t *client, char *msg) {
- if (client == NULL) {
- fprintf(stderr, "the client is NULL !\n");
- return;
- }
-
- write(client->fd, msg, strlen(msg));
- }
-
- static void write_body(client_t *client, char *msg) {
- char body_msg[strlen(msg) + 100];
- format_message(msg, body_msg);
-
- write_ori(client, body_msg);
- }
-
- static void read_cb(struct ev_loop *loop, ev_io *w, int revents) {
- client_t *client = w->data;
- int r = 0;
- char rbuff[1024];
- if (revents & EV_READ) {
- r = read(client->fd, &rbuff, 1024);
- }
-
- if (EV_ERROR & revents) {
- fprintf(stderr, "error event in read\n");
- free_res(loop, w);
- return ;
- }
-
- if (r < 0) {
- fprintf(stderr, "read error\n");
- ev_io_stop(EV_A_ w);
- free_res(loop, w);
- return;
- }
-
- if (r == 0) {
- fprintf(stderr, "client disconnected.\n");
- ev_io_stop(EV_A_ w);
- free_res(loop, w);
- return;
- }
-
- write_ori(client, HTMLFILE_RESPONSE_HEADER);
-
- char target_message[strlen(HTMLFILE_RESPONSE_FIRST) + 20];
- sprintf(target_message, "%X\r\n%s\r\n", (int)strlen(HTMLFILE_RESPONSE_FIRST), HTMLFILE_RESPONSE_FIRST);
-
- write_ori(client, target_message);
- incr_usr_num();
- }
-
- static void accept_cb(struct ev_loop *loop, ev_io *w, int revents) {
- struct sockaddr_in client_addr;
- socklen_t client_len = sizeof(client_addr);
- int client_fd = accept(w->fd, (struct sockaddr *) &client_addr, &client_len);
- if (client_fd == -1) {
- fprintf(stderr, "the client_fd is NULL !\n");
- return;
- }
-
- client_t *client = malloc(sizeof(client_t));
- client->fd = client_fd;
- if (setnonblock(client->fd) < 0)
- err(1, "failed to set client socket to non-blocking");
-
- client->ev_read.data = client;
-
- ev_io_init(&client->ev_read, read_cb, client->fd, EV_READ);
- ev_io_start(loop, &client->ev_read);
- }
-
- int main(int argc, char const *argv[]) {
- int ch;
- while ((ch = getopt(argc, argv, "p:")) != -1) {
- switch (ch) {
- case 'p':
- server_port = atoi(optarg);
- break;
- }
- }
-
- printf("start free -m is \n");
- system("free -m");
- loop = ev_default_loop(0);
- struct sockaddr_in listen_addr;
- int reuseaddr_on = 1;
- int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
- if (listen_fd < 0)
- err(1, "listen failed");
- if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
- err(1, "setsockopt failed");
-
- memset(&listen_addr, 0, sizeof(listen_addr));
- listen_addr.sin_family = AF_INET;
- listen_addr.sin_addr.s_addr = INADDR_ANY;
- listen_addr.sin_port = htons(server_port);
-
- if (bind(listen_fd, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) < 0)
- err(1, "bind failed");
- if (listen(listen_fd, 5) < 0)
- err(1, "listen failed");
- if (setnonblock(listen_fd) < 0)
- err(1, "failed to set server socket to non-blocking");
-
- ev_io_init(&ev_accept, accept_cb, listen_fd, EV_READ);
- ev_io_start(loop, &ev_accept);
- ev_loop(loop, 0);
-
- return 0;
- }
-
- static void free_res(struct ev_loop *loop, ev_io *w) {
- dec_usr_num();
- client_t *client = w->data;
- if (client == NULL) {
- fprintf(stderr, "the client is NULL !!!!!!");
- return;
- }
-
- ev_io_stop(loop, &client->ev_read);
-
- close(client->fd);
-
- free(client);
- }
编译
gcc server.c -o server ../include/libev.a -lm
运行
./server -p 8000
在源码中默认指定了8000端口,可以通过-p进行指定新的端口。 开启了8000端口进行监听请求,http协议处理类似于htmlfile chunked块编码传输。
测试服务器端程序
测试程序使用libevent框架,因其使用简单,提供丰富易用接口,但需要提前下载,手动安装:
wget https://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gztar xvf libevent-2.0.21-stable.tar.gzcd libevent-2.0.21-stable./configure --prefix=/usrmakemake install
注意make和make install需要root用户。
测试端程序
client1.c 源码:
点击(此处)折叠或打开
- #include <sys/types.h>
- #include <sys/time.h>
- #include <sys/queue.h>
- #include <stdlib.h>
- #include <err.h>
- #include <event.h>
- #include <evhttp.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <time.h>
- #include <pthread.h>
-
- #define BUFSIZE 4096
- #define NUMCONNS 62000
- #define SERVERADDR "192.168.190.133"
- #define SERVERPORT 8000
- #define SLEEP_MS 10
-
- char buf[BUFSIZE];
-
- int bytes_recvd = 0;
- int chunks_recvd = 0;
- int closed = 0;
- int connected = 0;
-
- void chunkcb(struct evhttp_request *req, void *arg) {
- int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
- bytes_recvd += s;
- chunks_recvd++;
- if (connected >= NUMCONNS && chunks_recvd % 10000 == 0)
- printf(">Chunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
- }
-
- void reqcb(struct evhttp_request *req, void *arg) {
- closed++;
- }
-
- int main(int argc, char **argv) {
- event_init();
- struct evhttp *evhttp_connection;
- struct evhttp_request *evhttp_request;
- char path[32]; // eg: "/test/123"
- int i;
- for (i = 1; i <= NUMCONNS; i++) {
- evhttp_connection = evhttp_connection_new(SERVERADDR, SERVERPORT);
- evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
- evhttp_request = evhttp_request_new(reqcb, NULL);
- evhttp_request->chunk_cb = chunkcb;
- sprintf(&path, "/test/%d", ++connected);
- if (i % 100 == 0) printf("Req: %s\t->\t%s\n", SERVERADDR, &path);
- evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
- evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
- event_loop( EVLOOP_NONBLOCK );
- if ( connected % 200 == 0 )
- printf("\nChunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
- usleep(SLEEP_MS * 1000);
- }
-
- event_dispatch();
- return 0;
- }
备注:这部分代码参考了A Million-user Comet Application with Mochiweb, Part 3 ,根据需要有所修改。
编译
gcc -o client1 client1.c -levent
运行
./client1
可能在64位系统会遇到找不到libevent-2.0.so.5情况,需要建立一个软连接
ln -s /usr/lib/libevent-2.0.so.5 /lib64/libevent-2.0.so.5
即可自动连接IP地址为192.168.190.133:8000的服务器端应用。
第一个遇到的问题:文件句柄受限
测试端程序输出
看看测试端程序client1输出的错误信息:
Chunks: 798 Bytes: 402990 Closed: 0Req: 192.168.190.133 -/test/900Req: 192.168.190.133 -/test/1000Chunks: 998 Bytes: 503990 Closed: 0[warn] socket: Too many open files[warn] socket: Too many open files[warn] socket: Too many open files
服务器端程序输出
服务器端最后一条日志为
online user 1018
两边都遇到了文件句柄打开的情况。
在服务器端查看已经连接,并且端口号为8000的所有连接数量:
netstat -nat|grep -i "8000"|wc -l 1019
但与服务器端输出数量对不上,增加所有已经建立连接的选项:
netstat -nat|grep -i "8000"|grep ESTABLISHED|wc -l 1018
那么剩下的一条数据到底是什么呢?
netstat -nat|grep -i "8000"|grep -v ESTABLISHEDtcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN
也就是server.c监听的端口,数量上对的上。
在测试服务器端,查看测试进程打开的文件句柄数量
lsof -n|grep client1|wc -l1032
再次执行
ulimit -n1024
也是就是client1应用程序共打开了1032个文件句柄,而不是1024,为什么?
把当前进程所有打开的文件句柄保存到文件中,慢慢研究 lsof -n|grep client1 > testconnfinfo.txt
导出的文件可以参考: https://gist.github.com/yongboy/5260773
除了第一行,我特意添加上供友善阅读的头部列定义,也就是1032行信息,但是需要注意头部:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEclient1 3088 yongboy cwd DIR 253,0 4096 800747 /home/yongboy/workspace/c_socket.io_server/testclient1 3088 yongboy rtd DIR 253,0 4096 2 /test_connclient1 3088 yongboy txt REG 253,0 9697 799991 /home/yongboy/workspace/c_socket.io_server/test/test_conn_1client1 3088 yongboy mem REG 253,0 156872 50404 /lib64/ld-2.12.soclient1 3088 yongboy mem REG 253,0 1922152 78887 /lib64/libc-2.12.soclient1 3088 yongboy mem REG 253,0 145720 76555 /lib64/libpthread-2.12.soclient1 3088 yongboy mem REG 253,0 47064 69491 /lib64/librt-2.12.soclient1 3088 yongboy mem REG 253,0 968730 26292 /usr/lib/libevent-2.0.so.5.1.9client1 3088 yongboy 0u CHR 136,2 0t0 5 /dev/pts/2client1 3088 yongboy 1u CHR 136,2 0t0 5 /dev/pts/2client1 3088 yongboy 2u CHR 136,2 0t0 5 /dev/pts/2client1 3088 yongboy 3u REG 0,9 0 4032 anon_inodeclient1 3088 yongboy 4u unix 0xffff88007c82f3c0 0t0 79883 socketclient1 3088 yongboy 5u unix 0xffff880037c34380 0t0 79884 socketclient1 3088 yongboy 6u IPv4 79885 0t0 TCP 192.168.190.134:58693->192.168.190.133:irdmi (ESTABLISHED)client1 3088 yongboy 7u IPv4 79889 0t0 TCP 192.168.190.134:58694->192.168.190.133:irdmi (ESTABLISHED)client1 3088 yongboy 8u IPv4 79891 0t0 TCP 192.168.190.134:58695->192.168.190.133:irdmi (ESTABLISHED)client1 3088 yongboy 9u IPv4 79893 0t0 TCP 192.168.190.134:58696->192.168.190.133:irdmi (ESTABLISHED)
可以看到文件句柄是从0u开始,0u上面的8个(5个mem + 3个启动)进程,1032 - 8 = 1024个文件句柄,这样就和系统限制的值吻合了。
root用户编辑/etc/security/limits.conf文件添加:
* soft nofile 1048576* hard nofile 1048576
- soft是一个警告值,而hard则是一个真正意义的阀值,超过就会报错。
- soft 指的是当前系统生效的设置值。hard 表明系统中所能设定的最大值
- nofile - 打开文件的最大数目
- 星号表示针对所有用户,若仅针对某个用户登录ID,请替换星号
注意:
1024K x 1024 = 1048576K = 1M,1百万多一点。
备注:测试端和服务器端都需要作此设置,保存退出,然后reboot即可生效。
第一个问题,就这样克服了。再次运行 /client1测试程序,就不会出现受打开文件句柄的限制。但大概在测试端打开对外28200个端口时,会出现程序异常,直接退出。
段错误
这个也是程序没有处理端口不够用的异常,但可以通过增加端口进行解决。
备注: 但测试端单机最多只能打开6万多个连接,是一个问题,如何克服,下一篇解决此问题,并且还会遇到文件句柄的受限问题。
100万并发连接服务器笔记之处理端口数量受限问题
第二个遇到的问题:端口数量受限
一般来说,单独对外提供请求的服务不用考虑端口数量问题,监听某一个端口即可。但是向提供代理服务器,就不得不考虑端口数量受限问题了。当前的1M并发连接测试,也需要在客户端突破6万可用端口的限制。
单机端口上限为65536
端口为16进制,那么2的16次方值为65536,在linux系统里面,1024以下端口都是超级管理员用户(如root)才可以使用,普通用户只能使用大于1024的端口值。
系统提供了默认的端口范围:
cat /proc/sys/net/ipv4/iplocalport_range
32768 61000
大概也就是共61000-32768=28232个端口可以使用,单个IP对外只能发送28232个TCP请求。
以管理员身份,把端口的范围区间增到最大:
echo "1024 65535"> /proc/sys/net/ipv4/iplocalport_range
现在有64511个端口可用.
以上做法只是临时,系统下次重启,会还原。 更为稳妥的做法是修改/etc/sysctl.conf文件,增加一行内容
net.ipv4.iplocalport_range = 1024 65535
保存,然后使之生效:
sysctl -p
现在可以使用的端口达到64510个(假设系统所有运行的服务器是没有占用大于1024的端口的,较为纯净的centos系统可以做到),要想达到50万请求,还得再想办法。
增加IP地址
一般假设本机网卡名称为 eth0,那么手动再添加几个虚拟的IP:
ifconfig eth0:1 192.168.190.151
ifconfig eth0:2 192.168.190.152 ......
或者偷懒一些:
for i in `seq 1 9`; do ifconfig eth0:$i 192.168.190.15$i up ; done
这些虚拟的IP地址,一旦重启,或者 service network restart 就会丢失。
为了模拟较为真实环境,在测试端,手动再次添加9个vmware虚拟机网卡,每一个网卡固定一个IP地址,这样省去每次重启都要重新设置的麻烦。
192.168.190.134
192.168.190.143
192.168.190.144
192.168.190.145
192.168.190.146
192.168.190.147
192.168.190.148
192.168.190.149
192.168.190.150
192.168.190.151
在server服务器端,手动添加桥接网卡和NAT方式网卡
192.168.190.230192.168.190.24010.95.20.250
要求测试端和服务器端彼此双方都是可以ping通。
网络四元组/网络五元组
四元组是指的是
{源IP地址,源端口,目的IP地址,目的端口}
五元组指的是(多了协议)
{源IP地址,目的IP地址,协议号,源端口,目的端口}
一个TCP连接的套接字对(socket pari)是一个定义该连接的两个端点的四元组,即本地IP地址、本地TCP端口号、外地IP地址、外地TCP端口号。套接字对唯一标识一个网络上的每个TCP连接。
......
标识每个端点的两个值(IP地址和端口号)通常称为一个套接字。
以下以四元组为准。在测试端四元组可以这样认为:
{本机IP地址,本机端口,目的IP地址,目的端口}
请求的IP地址和目的端口基本上是固定的,不会变化,那么只能从本机IP地址和本机端口上考虑,端口的范围一旦指定了,那么增加IP地址,可以增加对外发出的请求数量。假设系统可以使用的端口范围已经如上所设,那么可以使用的大致端口为64000个,系统添加了10个IP地址,那么可以对外发出的数量为 64000 * 10 = 640000,数量很可观。
只有{源IP地址,源端口}确定对外TCP请求数量
经测试,四元组里面,只有{源IP地址,源端口}才能够确定对外发出请求的数量,跟{目的IP地址,目的端口}无关。
测试环境
在server端,并且启动./server两次,分别绑定8000端口和9000端口
./server -p 8000./server -p 9000
本机IP、端口绑定测试程序
这里写一个简单的测试绑定本机IP地址和指定端口的客户端测试程序。?
点击(此处)折叠或打开
- #include <sys/types.h>
- #include <sys/time.h>
- #include <sys/queue.h>
- #include <stdlib.h>
- #include <err.h>
- #include <event.h>
- #include <evhttp.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <time.h>
- #include <pthread.h>
- #include <errno.h>
-
- #define BUFSIZE 4096
- #define SLEEP_MS 10
-
- char buf[BUFSIZE];
-
- int bytes_recvd = 0;
- int chunks_recvd = 0;
-
- void chunkcb(struct evhttp_request *req, void *arg) {
- int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
- bytes_recvd += s;
- chunks_recvd++;
- printf(">Chunks: %d\tBytes: %d\n", chunks_recvd, bytes_recvd);
- }
-
- void reqcb(struct evhttp_request *req, void *arg) {
- fprintf(stderr, ">Now closed\n");
- exit(-1);
- }
-
- void err_cb(int err){
- fprintf(stderr, "setup failed(errno = %d): %s", errno, strerror(errno));
- }
-
- int main(int argc, char **argv) {
- char server_ip[16] = "";
- int server_port = 0;
-
- char local_ip[16] = "";
- int local_port = 0;
-
- int ch;
- while ((ch = getopt(argc, argv, "h:p:c:o:")) != -1) {
- switch (ch) {
- case 'h':
- printf("remote host is %s\n", optarg);
- strncpy(server_ip, optarg, 15);
- break;
- case 'p':
- printf("remote port is %s\n", optarg);
- server_port = atoi(optarg);
- break;
- case 'c':
- printf("local ip is %s\n", optarg);
- strncpy(local_ip, optarg, 15);
- break;
- case 'o':
- printf("local port is %s\n", optarg);
- local_port = atoi(optarg);
-
- break;
- }
- }
-
- event_init();
- event_set_fatal_callback(err_cb);
- struct evhttp *evhttp_connection;
- struct evhttp_request *evhttp_request;
- char path[32];
-
- evhttp_connection = evhttp_connection_new(server_ip, server_port);
- evhttp_connection_set_local_address(evhttp_connection, local_ip);
- evhttp_connection_set_local_port(evhttp_connection, local_port);
- evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
- evhttp_request = evhttp_request_new(reqcb, NULL);
- evhttp_request->chunk_cb = chunkcb;
- sprintf(&path, "/test/%d", local_port);
-
- evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
- evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
- event_loop( EVLOOP_NONBLOCK );
-
- usleep(SLEEP_MS * 10);
-
- event_dispatch();
-
- return 0;
- }
可以看到libevent-*/include/event2/http.h内置了对绑定本地IP地址的支持:
/** sets the ip address from which http connections are made */void evhttp_connection_set_local_address(struct evhttp_connection *evcon,const char *address);
不用担心端口,系统自动自动随机挑选,除非需要特别指定:
/** sets the local port from which http connections are made */void evhttp_connection_set_local_port(struct evhttp_connection *evcon,ev_uint16_t port);
编译
gcc -o client3 client3.c -levent
client3运行参数为
- -h 远程主机IP地址
- -p 远程主机端口
- -c 本机指定的IP地址(必须可用)
- -o 本机指定的端口(必须可用)
测试用例,本机指定同样的IP地址和端口,但远程主机和IP不一样.
在一个测试端打开一个终端窗口1,切换到 client3对应位置
./client3 -h 192.168.190.230 -p 8000 -c 192.168.190.148 -o 4000
输出为
remote host is 192.168.190.230remote port is 8000local ip is 192.168.190.148local port is 4000>Chunks: 1 Bytes: 505
再打开一个测试端终端窗口2,执行:
./client3 -h 192.168.190.240 -p 9000 -c 192.168.190.148 -o 4000
窗口2程序,无法执行,自动退出。
接着在窗口2终端继续输入:
./client3 -h 192.168.190.230 -p 8000 -c 192.168.190.148 -o 4001
注意,和窗口1相比,仅仅改变了端口号为4001。但执行结果,和端口1输出一模一样,在等待接收数据,没有自动退出。
剩下的,无论怎么组合,怎么折腾,只要一对{本机IP,本机端口}被占用,也就意味着对应一个具体的文件句柄,那么其它程序将不能够再次使用。
Java怎么绑定本地IP地址?
java绑定就很简单,但有些限制,不够灵活,单纯从源码中看不出来,api doc可以告诉我们一些事情。 打开JDKAPI1_6zhCN.CHM,查看InetSocketAddress类的构造函数说明:
public InetSocketAddress(InetAddress addr, int port)
根据 IP 地址和端口号创建套接字地址。 有效端口值介于 0 和 65535 之间。端口号 zero 允许系统在 bind 操作中挑选暂时的端口。null 地址将分配通配符 地址。
参数:
addr - IP 地址
port - 端口号
抛出:
IllegalArgumentException - 如果 port 参数超出有效端口值的指定范围。public InetSocketAddress(String hostname, int port)
根据主机名和端口号创建套接字地址。
尝试将主机名解析为 InetAddress。如果尝试失败,则将地址标记为未解析。如果存在安全管理器,则将主机名用作参数调用其 checkConnect 方法,以检查解析它的权限。这可能会导致 SecurityException 异常。
有效端口值介于 0 和 65535 之间。端口号 zero 允许系统在 bind 操作中挑选暂时的端口。
参数: hostname - 主机名
port - 端口号
抛出:
IllegalArgumentException - 如果 port 参数超出有效端口值的范围,或者主机名参数为 null。
SecurityException - 如果存在安全管理器,但拒绝解析主机名的权限。
另请参见:
isUnresolved()
InetSocketAddress的两个构造函数都支持,看情况使用。注意int port传递值为0,即可做到系统随机挑选端口。追踪一下源代码,发现最终调用
private native void socketBind(InetAddress address, int port) throws IOException;
如何查看socketBind的原始C代码,我就不清楚了,您若知晓,希望指教一下。 构造一个InetSocketAddress对象:
SocketAddress localSocketAddr = new InetSocketAddress("192.168.190.143", 0);
然后传递给需要位置即可。诸如使用netty连接到某个服务器上,在connect时指定远方地址,以及本机地址
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) Attempts a new connection with the specified remoteAddress and the specified localAddress.
Netty 客户端连接API见: http://docs.jboss.org/netty/3.2/api/org/jboss/netty/bootstrap/ClientBootstrap.html
Linux支持绑定本机IP、端口原理
说是原理,有些牵强,因为linux C提供了如何绑定函数,框架或者高级语言再怎么封装,在linux平台下面,需要这么调用:
struct sockaddr_in clnt_addr;....clnt_addr.sin_family = AF_INET;clnt_addr.sin_addr.s_addr = INADDR_ANY; //绑定本机IP地址clnt_addr.sin_port = htons(33333); //绑定本机端口if (bind(sockfd, (struct sockaddr *) &clnt_addr,sizeof(clnt_addr)) < 0) error("ERROR on binding");if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting");.......
构造一个clnt_addr结构体,本地IP或者端口赋值,在connect之前,先bind,就这么简单。
更完整例子,可以参考 http://stackoverflow.com/questions/4852256/need-a-complete-snippet-example-of-binding-tcp-client-socket
有关端口的问题,到此为止,下一篇,回到测试。
100万并发连接服务器笔记之测试端就绪
重新编写测试端程序
测试端程序需要增加绑定本机IP和本地端口的功能,以尽可能的向外发出更多的tcp请求。需要对client1.c重构,增加参数传递。 下面是client2.c的代码?
点击(此处)折叠或打开
- #include <sys/types.h>
- #include <sys/time.h>
- #include <sys/queue.h>
- #include <stdlib.h>
- #include <err.h>
- #include <event.h>
- #include <evhttp.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <time.h>
- #include <pthread.h>
-
- #define BUFSIZE 4096
- #define SLEEP_MS 10
-
- char buf[BUFSIZE];
-
- int bytes_recvd = 0;
- int chunks_recvd = 0;
- int closed = 0;
- int connected = 0;
-
- static char ip_array[300] = "192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.151,192.168.190.152";
- static char server_ip[16] = "192.168.190.133";
- static int server_port = 8000;
- static int max_conns = 62000;
-
- // called per chunk received
- void chunkcb(struct evhttp_request *req, void *arg) {
- int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
- bytes_recvd += s;
- chunks_recvd++;
- if (connected >= max_conns && chunks_recvd % 10000 == 0)
- printf(">Chunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
- }
-
- // gets called when request completes
- void reqcb(struct evhttp_request *req, void *arg) {
- closed++;
- }
-
- int main(int argc, char **argv) {
- int ch;
- while ((ch = getopt(argc, argv, "o:h:p:m:")) != -1) {
- switch (ch) {
- case 'h':
- printf("host is %s\n", optarg);
- strncpy(server_ip, optarg, 15);
- break;
- case 'p':
- printf("port is %s\n", optarg);
- server_port = atoi(optarg);
- /*strncpy(server_ip, optarg, 15);*/
- break;
- case 'm':
- printf("max_conns is %s\n", optarg);
- max_conns = atoi(optarg);
- /*strncpy(server_ip, optarg, 15);*/
- break;
- case 'o':
- printf("ori_ips is %s\n", optarg);
-
- strncpy(ip_array, optarg, 300 - 1);
- break;
- }
- }
-
- event_init();
- struct evhttp *evhttp_connection;
- struct evhttp_request *evhttp_request;
- char path[32];
- int i;
-
- char delims[] = ",";
- char *ori_ip = NULL;
- ori_ip = strtok( ip_array, delims );
- while (ori_ip != NULL) {
- for (i = 1; i <= max_conns; i++) {
- evhttp_connection = evhttp_connection_new(server_ip, server_port);
- evhttp_connection_set_local_address(evhttp_connection, ori_ip);
- evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
- evhttp_request = evhttp_request_new(reqcb, NULL);
- evhttp_request->chunk_cb = chunkcb;
- sprintf(&path, "/test/%d", ++connected);
-
- if (i % 1000 == 0)
- printf("Req: %s\t->\t%s\n", ori_ip, &path);
-
- evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
- evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
- event_loop( EVLOOP_NONBLOCK );
-
- if ( connected % 1000 == 0 )
- printf("\nChunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
-
- usleep(SLEEP_MS * 10);
- }
-
- ori_ip = strtok( NULL, delims );
- }
-
- event_dispatch();
-
- return 0;
- }
若不指定端口,系统会随机挑选没有使用到的端口,可以节省些心力。
编译:
gcc -o client2 client2.c -levent
参数解释
- -h 要连接的服务器IP地址
- -p 要连接的服务器端口
- -m 本机IP地址需要绑定的随机端口数量
- -o 本机所有可用的IP地址列表,注意所有IP地址都应该可用
运行:
./client2 -h 192.168.190.230 -p 8000 -m 64000 -o 192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.150,192.168.190.151
太长了,每次执行都要粘贴过去,直接放在一个client2.sh文件中,执行就很简单方便多了。
#!/bin/sh./client2 -h 192.168.190.230 -p 8000 -m 64000 -o 192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.150,192.168.190.151
保存,赋值可运行:
chmod +x client2.sh
启动测试:
sh client2.sh
第三个遇到的问题:fs.file-max的问题
测试端程序client2.c在发出的数量大于某个值(大概为40万时)是,通过dmesg命令查看会得到大量警告信息:
[warn] socket: Too many open files in system
此时,就需要检查/proc/sys/fs/file-max参数了。
查看一下系统对fs.file-max的说明
/proc/sys/fs/file-maxThis file defines a system-wide limit on the number of open files for all processes. (See also setrlimit(2), which can be used by a process to set the per-process limit,RLIMIT_NOFILE, on the number of files it may open.) If you get lots of error messages about running out of file handles, try increasing this value:echo 100000 > /proc/sys/fs/file-maxThe kernel constant NR_OPEN imposes an upper limit on the value that may be placed in file-max.If you increase /proc/sys/fs/file-max, be sure to increase /proc/sys/fs/inode-max to 3-4 times the new value of /proc/sys/fs/file-max, or you will run out of inodes.
file-max表示系统所有进程最多允许同时打开所有的文件句柄数,系统级硬限制。Linux系统在启动时根据系统硬件资源状况计算出来的最佳的最大同时打开文件数限制,如果没有特殊需要,不用修改,除非打开的文件句柄数超过此值。
在为测试机分配4G内存时,对应的fs.file-max值为386562,很显然打开的文件句柄很受限,38万个左右。 很显然,无论是测试端还是服务端,都应该将此值调大些,一定要大于等于/etc/security/limits.conf送所设置的soft nofile和soft nofile值。
注意ulimit -n,仅仅设置当前shell以及由它启动的进程的资源限制。
备注:以上参数,具有包含和被包含的关系。
当前会话修改,可以这么做:
echo 1048576 > /proc/sys/fs/file-max
但系统重启后消失。
永久修改,要添加到 /etc/sysctl.conf 文件中:
fs.file-max = 1048576
保存并使之生效:
sysctl -p
再测,就不会出现此问题了。
一台6G内存机器测试机,分配7个网卡,可以做到不占用虚拟内存,对外发出64000 * 7 = 448000个对外持久请求。要完成100万的持久连接,还得再想办法。
最终测试端组成如下:
- 两台物理机器各自一个网卡,每个发出64000个请求
- 两个6G左右的centos测试端机器(绑定7个桥接或NAT连接)各自发出64000*7 = 448000请求
- 共使用了16个网卡(物理网卡+虚拟网卡)
- 1M ≈ 1024K ≈ 1024000 = (64000) + (64000) + (64000*7) + (64000*7)
- 共耗费16G内存,16个网卡(物理+虚拟),四台测试机
备注:
下面就要完成1M持久连接的目标,但在服务端还会遇到最后一个问题。
100万并发连接服务器笔记之1M并发连接目标达成
第四个遇到的问题:tcp_mem
在服务端,连接达到一定数量,诸如50W时,有些隐藏很深的问题,就不断的抛出来。 通过查看dmesg命令查看,发现大量TCP: too many of orphaned sockets错误,也很正常,下面到了需要调整tcp socket参数的时候了。
第一个需要调整的是tcp_rmem,即TCP读取缓冲区,单位为字节,查看默认值
cat /proc/sys/net/ipv4/tcp_rmem4096 87380 4161536
默认值为87380bit ≈ 86K,最小为4096bit=4K,最大值为4064K。
第二个需要调整的是tcp_wmem,发送缓冲区,单位是字节,默认值
cat /proc/sys/net/ipv4/tcp_wmem4096 16384 4161536
解释同上
第三个需要调整的tcp_mem,调整TCP的内存大小,其单位是页,1页等于4096字节。系统默认值:
cat /proc/sys/net/ipv4/tcp_mem932448 1243264 1864896
tcp_mem(3个INTEGER变量):low, pressure, high
- low:当TCP使用了低于该值的内存页面数时,TCP不会考虑释放内存。
- pressure:当TCP使用了超过该值的内存页面数量时,TCP试图稳定其内存使用,进入pressure模式,当内存消耗低于low值时则退出pressure状态。
- high:允许所有tcp sockets用于排队缓冲数据报的页面量,当内存占用超过此值,系统拒绝分配socket,后台日志输出“TCP: too many of orphaned sockets”。
一般情况下这些值是在系统启动时根据系统内存数量计算得到的。 根据当前tcp_mem最大内存页面数是1864896,当内存为(1864896*4)/1024K=7284.75M时,系统将无法为新的socket连接分配内存,即TCP连接将被拒绝。
实际测试环境中,据观察大概在99万个连接左右的时候(零头不算),进程被杀死,触发out of socket memory错误(dmesg命令查看获得)。每一个连接大致占用7.5K内存(下面给出计算方式),大致可算的此时内存占用情况(990000 * 7.5 / 1024K = 7251M)。
这样和tcp_mem最大页面值数量比较吻合,因此此值也需要修改。
三个TCP调整语句为:
echo "net.ipv4.tcp_mem = 786432 2097152 3145728">> /etc/sysctl.confecho "net.ipv4.tcp_rmem = 4096 4096 16777216">> /etc/sysctl.confecho "net.ipv4.tcp_wmem = 4096 4096 16777216">> /etc/sysctl.conf
备注: 为了节省内存,设置tcp读、写缓冲区都为4K大小,tcp_mem三个值分别为3G 8G 16G,tcp_rmem和tcp_wmem最大值也是16G。
目标达成
经过若干次的尝试,最终达到目标,1024000个持久连接。1024000数字是怎么得来的呢,两台物理机器各自发出64000个请求,两个配置为6G左右的centos测试端机器(绑定7个桥接或NAT连接)各自发出640007 = 448000。也就是 1024000 = (64000) + (64000) + (640007) + (64000*7), 共使用了16个网卡(物理网卡+虚拟网卡)。
终端输出
......online user 1023990online user 1023991online user 1023992online user 1023993online user 1023994online user 1023995online user 1023996online user 1023997online user 1023998online user 1023999online user 1024000
在线用户目标达到1024000个!
服务器状态信息
服务启动时内存占用:
total used free shared buffers cached Mem: 10442 271 10171 0 22 78 -/+ buffers/cache: 171 10271 Swap: 8127 0 8127
系统达到1024000个连接后的内存情况(执行三次 free -m 命令,获取三次结果):
total used free shared buffers cached Mem: 10442 7781 2661 0 22 78 -/+ buffers/cache: 7680 2762 Swap: 8127 0 8127 total used free shared buffers cached Mem: 10442 7793 2649 0 22 78 -/+ buffers/cache: 7692 2750 Swap: 8127 0 8127 total used free shared buffers cached Mem: 10442 7804 2638 0 22 79 -/+ buffers/cache: 7702 2740 Swap: 8127 0 8127
虚拟机运行Centos内存占用,不太稳定,但一般相差不大,以上数值,仅供参考。
执行top -p 某刻输出信息:
top - 17:23:17 up 18 min, 4 users, load average: 0.33, 0.12, 0.11 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.2%us, 6.3%sy, 0.0%ni, 80.2%id, 0.0%wa, 4.5%hi, 8.8%si, 0.0%st Mem: 10693580k total, 6479980k used, 4213600k free, 22916k buffers Swap: 8323056k total, 0k used, 8323056k free, 80360k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2924 yongboy 20 0 82776 74m 508 R 51.3 0.7 3:53.95 server
执行vmstate:
vmstatprocs -----------memory---------- ---swap-- -----io---- --system-- -----cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 0 0 0 2725572 23008 80360 0 0 21 2 1012 894 0 9 89 2 0
获取当前socket连接状态统计信息:
cat /proc/net/sockstatsockets: used 1024380TCP: inuse 1024009 orphan 0 tw 0 alloc 1024014 mem 2UDP: inuse 11 mem 1UDPLITE: inuse 0RAW: inuse 0FRAG: inuse 0 memory 0
获取当前系统打开的文件句柄:
sysctl -a | grep filefs.file-nr = 1025216 0 1048576fs.file-max = 1048576
此时任何类似于下面查询操作都是一个慢,等待若干时间还不见得执行完毕。
netstat -nat|grep -i "8000"|grep ESTABLISHED|wc -l netstat -n | grep -i "8000" | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
以上两个命令在二三十分钟过去了,还未执行完毕,只好停止。
小结
本次从头到尾的测试,所需要有的linux系统需要调整的参数也就是那么几个,汇总一下:
echo "yongboy soft nofile 1048576" >> /etc/security/limits.conf echo "yongboy hard nofile 1048576" >> /etc/security/limits.conf echo "fs.file-max = 1048576" >> /etc/sysctl.conf echo "net.ipv4.ip_local_port_range = 1024 65535" >> /etc/sysctl.conf echo "net.ipv4.tcp_mem = 786432 2097152 3145728" >> /etc/sysctl.conf echo "net.ipv4.tcp_rmem = 4096 4096 16777216" >> /etc/sysctl.conf echo "net.ipv4.tcp_wmem = 4096 4096 16777216" >> /etc/sysctl.conf
其它没有调整的参数,仅仅因为它们暂时对本次测试没有带来什么影响,实际环境中需要结合需要调整类似于SO_KEEPALIVE、tcpmax_orphans等大量参数。
本文代表一次实践,不足之处,欢迎批评指正。
- 100万并发连接服务器
- 100万并发连接服务器笔记之测试端就绪
- 100万并发连接服务器笔记之准备篇
- 一 100万并发连接服务器笔记之准备篇
- 一 100万并发连接服务器笔记之准备篇
- 100万并发连接服务器笔记之准备篇
- 100万并发连接服务器笔记之测试端就绪
- 100万并发连接服务器笔记之准备篇
- 100万并发连接服务器笔记之Erlang完成1M并发连接目标
- 100万并发连接服务器笔记之1M并发连接目标达成
- 100万并发连接服务器笔记之Erlang完成1M并发连接目标
- 四 100万并发连接服务器笔记之1M并发连接目标达成
- 六 100万并发连接服务器笔记之Erlang完成1M并发连接目标
- 100万并发连接服务器笔记之1M并发连接目标达成
- 100万并发连接服务器笔记之1M并发连接目标达成
- 100万并发连接服务器笔记之1M并发连接
- 100万并发连接服务器笔记之1M并发连接目标达成
- 100万并发连接服务器笔记之1M并发连接目标达成
- 精准测分:基于函数调用关系链的用例消振算法(上帝视角)
- 图像局部显著性—点特征(GLOH)
- PHP CURL学习
- UIButton的基础
- 平ip,看是否能ping通的方法
- 100万并发连接服务器
- Spring IOC容器基本原理
- poj 1984 Navigation Nightmare(带权并查集)
- Python 异常
- 如何理解TensorFlow,TensorFlow在神经网络训练中的作用是什么?
- SQL SERVER 2008 安装图解
- Dubbo实战(一)快速入门
- SSL 1579_泽泽在巴西_计算几何+spfa
- 编辑视频