首先web.xml添加支持
<!-- 添加websocket支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
配置socket
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();
}
}
创建socket
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint(value = "/websocket/{user}")
@Component
public class MyWebSocket {
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
public static ConcurrentHashMap<String,MyWebSocket> webSocketSet = new ConcurrentHashMap<String,MyWebSocket>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 传过来的用户
*/
private String user = "";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(@PathParam(value = "user") String param, Session session) {
//接收到发送消息的人员编号
user = param;
this.session = session;
/**加入set中*/
webSocketSet.put(param,this);
/**在线数加1*/
addOnlineCount();
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("-连接已建立-");
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!user.equals("")) {
/** 从set中删除 */
webSocketSet.remove(user);
/** 在线数减1 */
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
try {
this.sendMessage(message);
String sendUserno = message.split("[;]")[0];
// String sendMessage = message.split("[;]")[1];
// webSocketSet.get(sendUserno).sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
}
// //群发消息
// for (MyWebSocket item : webSocketSet) {
// try {
// item.sendMessage(message);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
/**
* 发生错误时调用
* **/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
/**
* 给指定的人发送消息
* @param message
*/
private void sendToUser(String message) {
String sendUserno = message.split("[;]")[0];
String sendMessage = message.split("[;]")[1];
try {
if (webSocketSet.get(sendUserno) != null) {
webSocketSet.get(sendUserno).sendMessage( "用户" + user + "发来消息:" + " <br/> " + sendMessage);
} else {
System.out.println("当前用户不在线");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
for (MyWebSocket item : webSocketSet.values()) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
html页面
<!DOCTYPE HTML>
<html>
<head>
<title> WebSocket</title>
<style>
body{padding: 20px;background: #f5f5f5;}
#message{border: 1px dashed skyblue;padding: 20px;min-height: 300px;background: white;}
p{border-bottom: 1px dashed cornflowerblue;;}
</style>
</head>
<br />
<body>
<div>
<b>WebSocket</b><br />
<input id="text" type="text" placeholder="请输入内容"/><button id="con" onclick="send()">发送</button> <button id="con" onclick="connect()">连接socke</button>
<button class="btn btn-info btn-sm" onclick="closeWebSocket()">关闭连接</button>
<button class="btn btn-warning btn-sm" onclick="clearMsg()">清屏</button>
<br /><br />
</div>
<div id="message">
</div>
</body>
<div th:include="include/footer_js::footer"></div>
<script type="text/javascript">
var websocket = null;
var user=new Date().getTime();
//判断当前浏览器是否支持WebSocket
function connect(){
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8099/websocket/"+user);
$("#con").attr("disabled","disabled");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("连接成功!");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML("<p>"+event.data+"</p>");
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
$("#con").removeAttr("disabled");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
setMessageInnerHTML("已关闭!");
}
function clearMsg(){
$('#message').empty();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
message=user+";"+message;
websocket.send(message);
}
</script>
</html>
针对于多个终端,所以在初始化和发消息时,传递一个值作为用户标识。