创建WebSocket 类
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import javassist.tools.web.Webserver;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/** web socket
* Created by z1761 on 2018/11/2.
*/
@ServerEndpoint(value="/websocket/{username}")
@Component
public class WebSocket {
private static int onlineCount = 0; //做统计使用
private static Map<String,WebSocket> socket = new ConcurrentHashMap<>();
//private static CopyOnWriteArraySet<WebSocket> socket = new CopyOnWriteArraySet<>();
private Session session;
private String username;
private static int count =0;
@OnOpen
public void onOpen(@PathParam("username")String username, Session session){
this.username = username;
this.session = session;
/* count++;
socket.put(count+"",this);*/
addOnlineCount();
System.out.println("已连接");
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
@OnClose
public void onClone(@PathParam("username")String username,Session session){
socket.remove(username);
removeOnlineCount();
System.out.println("断开连接");
}
@OnMessage
public void onMessage(String message){
System.out.println("来自客户端的消息:" + message);
/*for(Map<String,WebSocket> item: socket){
try {
// item.onMessage();
// item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}*/
//sendMessageAll("给所有人");
JSONObject json = JSONObject.parseObject(message);
if (!json.get("TO").equals("ALL")) {
sendMessageTo("给一个人",json.get("TO").toString());
} else {
sendMessageAll("给所有人");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
//添加连接数
public static synchronized void addOnlineCount(){
WebSocket.onlineCount++;
}
// 删除连接数
public static synchronized void removeOnlineCount(){
WebSocket.onlineCount--;
}
//给你一个发消息
public static void sendMessageTo(String message,String to){
for (WebSocket item : socket.values()) {
if (item.username.equals(to)) {
item.session.getAsyncRemote().sendText(message);
}
}
}
//群发消息
public static void sendMessageAll(String message){
for (WebSocket item :socket.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized Map<String,WebSocket> getClients(){
return socket;
}
}
创建 WebSocketConfig 类
/** 这个bean 告诉springboot 要支持websocket
*
* Created by z1761 on 2018/11/5.
*/
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
html类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<input name ="" id="user1" value="猪">
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket/"+"猪");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
//var message =
var shuzu ={};
shuzu.TO = "2";
shuzu.message = document.getElementById('text').value;
websocket.send(JSON.stringify(shuzu));
}
</script>
</html>