1.ningx配置
location ^~ /websocket {
access_log /var/log/nginx/come-websocket.log;
proxy_pass http://ip:port/websocket;
proxy_set_header Host $host;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'Upgrade';
}
为了建立一个 WebSocket 连接,
客户端浏览器首先要向服务器发起一个 HTTP 请求,
这个请求和通常的 HTTP 请求不同,包含了一些附加头信息,其中附加头信息"Upgrade: WebSocket"表明这是一个申请协议升级的 HTTP 请求
客户端请求
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
Sec-WebSocket-Version: 13
服务器回应
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=
Sec-WebSocket-Location: ws://example.com/
2.nginx 负载均衡
upstream websocketUp{
server ip1:port1;
server ip2:port2;
}
location ^~ /websocket {
access_log /var/log/nginx/come-websocket.log;
proxy_pass http://websocketUp/websocket;
proxy_set_header Host $host;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'Upgrade';
}
3.前端代码
<script type="text/javascript">
//连接websocket
var ws = null;
var lockReconnect = false;
var wsUrl = "ws://localhost:8080/websocket/userId";
createWebSocket(wsUrl);
function createWebSocket(url) {
try{
if('WebSocket' in window){
ws = new WebSocket(url);
}else if('MozWebSocket' in window){
ws = new MozWebSocket(url);
}else{
console.log("当前浏览器 Not support websocket");
}
initEventHandle();
}catch(e){
reconnect(url);
console.log(e);
}
}
function initEventHandle() {
ws.onclose = function () {
reconnect(wsUrl);
console.log("llws连接关闭!"+new Date().toUTCString());
};
ws.onerror = function () {
reconnect(wsUrl);
console.log("llws连接错误!");
};
ws.onopen = function () {
heartCheck.reset().start(); //心跳检测重置
console.log("llws连接成功!"+new Date().toUTCString());
};
ws.onmessage = function (event) { //如果获取到消息,心跳检测重置
heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
console.log("llws收到消息啦:" +event.data);
if(event.data!='tong'){
//处理消息
}
};
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
ws.close();
}
function reconnect(url) {
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
createWebSocket(url);
lockReconnect = false;
}, 2000);
}
//心跳检测
var heartCheck = {
timeout: 540000, //9分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
ws.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}
function closeWebSocket(){
ws.close();
}
</script>
4.后端代码
4.1.pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo-websocket-netty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-websocket-netty</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.2.配置
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.3服务接口
package com.example.demo.service;
public interface WebsocketService {
void sendMessageToUsers(String userIds,String message) throws Exception ;
}
4.4.websocket服务器
package com.example.demo.service.impl;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.assertj.core.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.example.demo.service.WebsocketService;
@ServerEndpoint("/websocket/{userId}") //WebSocket客户端建立连接的地址
@Service
@Scope(value="prototype")
public class WebsocketServiceImpl implements WebsocketService{
private final static Logger logger = LoggerFactory.getLogger(WebsocketServiceImpl.class);
private static CopyOnWriteArraySet<WebsocketServiceImpl> websockets = new CopyOnWriteArraySet<>();
private static int onlineCount = 0;
private Session session;
//用户ID
private String userId;
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.userId = userId;
this.session = session;
websockets.add(this);
addOnlineCount();
logger.info("有新连接加入!当前在线人数为:" + getOnlineCount()+",userId:"+this.userId);
}
@OnClose
public void onClose(){
websockets.remove(this); //从set中删除
subOnlineCount(); //在线数减1
logger.info("有一连接关闭!当前在线人数为:" + getOnlineCount()+",userId"+this.userId);
}
@OnMessage
public void onMessage(String message, Session session) {
String curId = session.getId();
for(WebsocketServiceImpl websocketService:websockets) {
if(curId.equals(websocketService.session.getId())) {
try {
websocketService.sendMessage("tong");
break;
} catch (IOException e) {
logger.info(this.userId+"onMessage连接发生了错误" + getOnlineCount());
e.printStackTrace();
continue;
}
}
}
}
@Override
public void sendMessageToUsers(String userIds,String message) throws Exception {
List<Object> userIdList = Arrays.asList(userIds.split(","));
for(WebsocketServiceImpl websocketService: websockets){
try {
if(userIdList.contains(websocketService.userId)){
websocketService.sendMessage(message);
System.out.println("向用户" + websocketService.userId + "推送消息"+message);
}
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}
@OnError
public void onError(Session session, Throwable error){
logger.info(this.userId+"onError连接发生了错误" + getOnlineCount());
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebsocketServiceImpl.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebsocketServiceImpl.onlineCount--;
}
}
4.5.控制器
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.service.WebsocketService;
@Controller
public class WebsocketController {
@Autowired
private WebsocketService websocketService;
@RequestMapping("/sendMessageToUsers")
public String sendMessageToUsers(String userIds,String message)throws Exception{
websocketService.sendMessageToUsers(userIds,message);
return "1";
}
}