用nginx配置websocket服务器

系统环境

ubuntu14.04 Desktop x64

编译nginx

apt-get安装的nginx并不支持websocket,需要添加nginx-push-stream-module模块,所以我们要重新编译nginx。

编译参考模块给出的 参考地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
git clone https://github.com/wandenberg/nginx-push-stream-module.git
# download nginx latest
wget http://nginx.org/download/nginx-1.9.10.tar.gz

# unpack, configure and build
tar zxvf nginx-1.9.10.tar.gz
cd nginx-1.9.10

# add Openssl model,generate Makefile
./configure --add-module=../nginx-push-stream-module --with-http_ssl_module

# if the HTTP rewrite module requires the PCRE library.
# sudo apt-get install libpcre3 libpcre3-dev
# sudo apt-get install openssl libssl-dev

make & sudo make install

更多config配置,使用./config –help默认安装在/usr/local/nginx下

配置websocket

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
# add the push_stream_shared_memory_size to your http context
http {
push_stream_shared_memory_size 32M;

# define publisher and subscriber endpoints in your server context
server {
location /channels-stats {
# activate channels statistics mode for this location
push_stream_channels_statistics;

# query string based channel id
push_stream_channels_path $arg_id;
}

location /pub {
# activate publisher (admin) mode for this location
push_stream_publisher admin;

# query string based channel id
push_stream_channels_path $arg_id;
}

location ~ /sub/(.*) {
# activate subscriber (streaming) mode for this location
push_stream_subscriber;

# positional channel path
push_stream_channels_path $1;
}
}
}

配置一个publisher,配置一个subscriber,以id区分每一个channel也可以直接nginx加载misc/nginx.conf

测试

推荐使用curl直接测试,也可以选择使用iocat测试,需要安装node.js以及npm

1
2
3
4
5
6
7
8
9
10
npm install iocat -g

# WebSocket Client
iocat ws://127.0.0.1:80/sub/1

# WebSocket Server
iocat -l -p 80

# or curl
curl -s -v -X POST 'http://127.0.0.1/pub?id=1' -d 'Hello World!'