设为首页 收藏本站
查看: 678|回复: 0

[经验分享] Reverse Proxy Web Sockets with Nginx and Socket.IO

[复制链接]

尚未签到

发表于 2015-11-13 13:59:25 | 显示全部楼层 |阅读模式

  最近一直在关注socket.io这个东西,看到一篇博客去仔细分析。引自:http://www.letseehere.com/reverse-proxy-web-sockets
  
  If you’re using Socket.io and want to reverse proxy your web socket connections, you’ll quickly find it’s somewhat difficult. Since web sockets are done over HTTP 1.1 connections (where the handshake and upgrade are completed), your backend needs to support
HTTP 1.1, and from what I have researched, they break the HTTP 1.0 spec (see
this discussion at stackoverflow).
  Some people have been able to get HAProxy to work for effective proxying of websocket connections, but I couldn’t get this to work reliably when I tried the latest version and TCP mode.
  If you’re using nginx, you won’t be able to proxy web socket connections using the standard nginx proxy_pass directives. Fortunately, Weibin Yao has developed a tcp proxy module for nginx that allows you to reverse proxy general tcp connections, especially
well suited for websockets.
  Let’s get a simple web socket proxy up and running. Download nginx sources and tcp_proxy module:

Compile Nginx with tcp_proxy module
  export NGINX_VERSION=1.0.4

curl -O http://nginx.org/download/nginx-$NGINX_VERSION.tar.gz

git clone https://github.com/yaoweibin/nginx_tcp_proxy_module.git

tar -xvzf nginx-$NGINX_VERSION.tar.gz

cd nginx-$NGINX_VERSION

patch -p1 < ../nginx_tcp_proxy_module/tcp.patch

./configure --add-module=../nginx_tcp_proxy_module/

sudo make && make install

Proxy Configuration
  Create a simple vhost like the following (note tcp must be defined at the server directive level):
  

tcp {
upstream websockets {
## node processes
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
server 127.0.0.1:8004;
check interval=3000 rise=2 fall=5 timeout=1000;
}   
server {
listen 127.0.0.1:80;
server_name _;
tcp_nodelay on;
proxy_pass websockets;
}
}
http {
## status check page for websockets
server {
listen 9000;
location /websocket_status {
check_status;
}
}
}
  

You’ll notice there is an additional http section, with a check_status directive. The tcp_proxy module provides a simple and convenient status check page which you can use to see if your backend node processes are up:
http://www.letseehere.com/wp-content/uploads/2011/06/Screen-shot-2011-06-18-at-10.20.26-PM.png

Create a Simple Websocket Server
  

var http = require('http'), io = require('socket.io');
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello world');
});
server.listen(process.argv[2]);
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
// new client is here!
console.log('client has connected');
client.on('message', function(){  })
});

  Start four node processes, each listening on different ports:
  node ./websocket-server.js 8001 &

node ./websocket-server.js 8002 &

node ./websocket-server.js 8003 &

node ./websocket-server.js 8004 &


  You should now check your status page to verify all backends are up and running:
http://www.letseehere.com/wp-content/uploads/2011/06/Screen-shot-2011-06-18-at-10.51.05-PM.png
  You can also go to our proxy via standard http (web browser) and correctly see “Hello World” to verify we’re hitting one of our node backends.

Test Websocket Proxying
  Now lets create a simple web socket client to test if we can actually create a websocket connection over the proxy:
  

<html>
<head>
<title>Websockets Proxy Test</title>
<script type=&quot;text/javascript&quot; src=&quot;sio.js&quot;></script>
<script type=&quot;text/javascript&quot;>
var socket = new io.Socket('ws://localhost');
socket.connect();
socket.on('connect', function() {
console.log('connected!');
});
</script>
</head>
<body>
<h1>Websockets Proxy Test</h1>
</body>
</html>

  
  
  
  For simplicity, I used a node static page server to serve this test page from the same node process and attached my Socket.IO instance to it:
  

var io = require('./Socket.IO-node');
var http = require(&quot;http&quot;),
url = require(&quot;url&quot;),
path = require(&quot;path&quot;),
fs = require(&quot;fs&quot;),
port = process.argv[2] || 8888;
var server = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {&quot;Content-Type&quot;: &quot;text/plain&quot;});
response.write(&quot;404 Not Found\n&quot;);
response.end();
return;
}   
if (fs.statSync(filename).isDirectory()) filename &#43;= '/index.html';
fs.readFile(filename, &quot;binary&quot;, function(err, file) {
if(err) {
response.writeHead(500, {&quot;Content-Type&quot;: &quot;text/plain&quot;});
response.write(err &#43; &quot;\n&quot;);
response.end();
return;
}   
response.writeHead(200);
response.write(file, &quot;binary&quot;);
response.end();
});
});
server.listen(parseInt(port, 10));
// socket.io
var socket = io.listen(server);

  
  
  
  Now, when we run our node instances:
  

node ./websocket-server.js 8001
Static file server running at
=> http://localhost:8001/
CTRL &#43; C to shutdown
info  - socket.io started

  
  
  
  And when we go to http://localhost, we can see successful websocket handshakes (which means we’re going over the nginx proxy):



debug - client authorized
info  - handshake authorized
info  - handshaken 5ec456d53d8dc0b43f61b5f3acdf8b8e

  
  
  
  Using this method you can successfully balance a cluster of web socket nodes, with some simple failure provided by the tcp_proxy module. Depending on the need and placement of nginx within your specific application stack, the ability to use this instead
of something like HAProxy or some other balancer strategy could allow scaling many more connections per server without introducing significant complexity.
  One thing that should be noted is you can no longer guarantee that a client will always connect to the same node process, like in the event of disconnection, so your application will need to understand this and implement session management across the cluster
(such as using a redis or memcache session store, for example).
  Happy hacking!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-138834-1-1.html 上篇帖子: nginx upload 模块build错误解决error: variable ‘result’ set but not used [-Werror=unuse 下篇帖子: 解剖Nginx·模块开发篇(3)ngx_http_hello_world_module 模块的基本函数实现
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表