websocket是html5中用来实现长连接的一个协议。
在同时使用nginx反向代理和websocket的时候,因为websocket的通信管道必须都要一直处于开启状态。
所以,有必要在nginx的配置文件中加入配置。
关键的地方笔者用红色标记出来:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
upstream netitcast.com { #服务器集群名字
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://netitcast.com;
proxy_redirect default;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
加上如上的两行红色的配置就可以放nginx支持websocket了,但是nginx的版本需在1.3以上。
但是吧项目跑起来的时候,发现还是报错了,
a:155 WebSocket connection to 'ws://localhost/bannerWs?id=1' failed: Error during WebSocket handshake: Unexpected response code: 403
截图如下:
经过一番搜索,原来是因为笔者使用了Spring-websocket。
Spring 默认的情况下会设置一个webSocket客户端的链接域的检查。
org.springframework.web.socket.server.support.OriginHandshakeInterceptor
这个类来检查客户端连接域是否和服务器的域是否一致,不一致,服务端就返回了403这个响应码。
我们只需要在注册Spring webSocketHandler 的时候,加入如下代码就可以了。
关键的地方,笔者用红色标出。
webSocketHandlerRegistry.addHandler(bannerWebSocketHandler, "/bannerWs").addInterceptors(new BannerWebSocketHandShaker()).setAllowedOrigins("http://localhost");
说明允许,的域是http://localhost ,这里说一下笔者自己跑的Tomcat的域是http://localhost:8080
处于不同一个域,所以,之前报http响应吗403,说是连接失败。