1、配置WebSocketConfig 类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
//如果需要引用service
// @Autowired
// public void socketAppTokenService(AppTokenService appTokenService) {
// WebSocketUtil.appTokenService = appTokenService;
// }
/**
* 服务器节点
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2、编写WebSocketUtil
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
@Slf4j
@ServerEndpoint("/ws")
@Component
public class WebSocketUtil {
private static int onlineCount = 0;//在线人数
private static CopyOnWriteArrayList<WebSocketUtil> webSocketSet = new CopyOnWriteArrayList<WebSocketUtil>();//在线用户集合
private Session session;//与某个客户端的连接会话
private String currentUser;
//如果需要引用service
//public static AppTokenService appTokenService;
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);//加入set中
addOnlineCount();
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
allCurrentOnline();
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
allCurrentOnline();
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
for (WebSocketUtil item : webSocketSet) {
try {
//编写业务
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("发生错误!");
throwable.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 获取当前所有在线用户名
*/
public static void allCurrentOnline() {
for (WebSocketUtil item : webSocketSet) {
System.out.println(item.currentUser);
}
}
/**
* 发送给指定用户
*/
public static void sendMessageTo(String message, String token) throws IOException {
for (WebSocketUtil item : webSocketSet) {
if (item.currentUser.equals(token)) {
System.out.println("token:" + message);
item.session.getBasicRemote().sendText(message);
}
}
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
System.out.println(message);
for (WebSocketUtil item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketUtil.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketUtil.onlineCount--;
}
3、
@Slf4j
@RestController
public class WebSocketController {
//给指定用户发
@LoginIgnore
@GetMapping("/send/{token}/{message}")
public R sendMessage(@PathVariable("message") String message, @PathVariable("token") String token) throws IOException {
WebSocketUtil.sendMessageTo(message,token)
return R.ok();
}
}
4、HTML测试
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Netty-Websocket</title>
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
//换成你的地址
socket = new WebSocket("ws://127.0.0.1:9331/ws");
socket.onmessage = function (event) {
var ta = document.getElementById('responseText');
let resData = JSON.parse(event.data);
console.log(resData);
ta.value += "消息: " + resData.proxy + "\t\t消息: " + resData.data + "\r\n";
};
socket.onopen = function (event) {
var ta = document.getElementById('responseText');
ta.value = "Netty-WebSocket服务器。。。。。。连接 \r\n";
};
socket.onclose = function (event) {
var ta = document.getElementById('responseText');
ta.value = "Netty-WebSocket服务器。。。。。。关闭 \r\n";
};
} else {
alert("您的浏览器不支持WebSocket协议!");
}
function send(proxy,token,data) {
if (!window.WebSocket) {
return;
}
let param={
proxy: proxy,
token: token,
data: data
}
if (socket.readyState == WebSocket.OPEN) {
let resData = JSON.stringify(param);
console.log(resData);
socket.send(resData);
} else {
alert("WebSocket 连接没有建立成功!");
}
}
</script>
</head>
<body>
<form onSubmit="return false;">
<div>
<label>proxy</label><input type="text" name="proxy" value="${proxy!!}"/> <br/>
<label>token</label><input type="text" name="token" value="${token!!}"/> <br/>
<label>data</label><input type="text" name="data" value="这里输入数据"/> <br/>
<br/> <input type="button" value="发送ws消息"
onClick="send(this.form.proxy.value, this.form.token.value,this.form.data.value)"/>
</div>
<hr color="black"/>
<h3>服务端返回的应答消息</h3>
<textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
</form>
</body>
</html>