支持websocket
nginx版本
- 要求 1.3.13以后的版本
html示例
socket = new WebSocket("ws://127.0.0.1/chat");
"ws:":websoket協(xié)議药蜻;
"127.0.0.1":nginx地址;
"chat":location指示器免猾,表示要轉(zhuǎn)向websoket服務企巢。
nginx.conf
http {
# websocket client請求頭自帶http_upgrade,映射成connection_upgrade
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
# chat 表示websocket請求
location /chat {
# 12345本機websocket 服務
proxy_pass http://127.0.0.1:12345;
proxy_http_version 1.1;
# 超時設置1小時
proxy_read_timeout 3600s;
# 啟用支持websocket連接,nginx的功能
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
java代碼websocket初始化
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("收到新連接");
//websocket協(xié)議本身是基于http協(xié)議的川慌,所以這邊也要使用http解編碼器
ch.pipeline().addLast(new HttpServerCodec());
//以塊的方式來寫的處理器
ch.pipeline().addLast(new ChunkedWriteHandler());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/chat", null, true, 65536 * 10));
ch.pipeline().addLast(new MyWebSocketHandler());
}
WebSocketServerProtocolHandler 指定 "/chat"
因為超時機制岸浑,超時后鏈路會斷開,可以服務端發(fā)送定時心跳硝逢。