1:引入jar包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2:配置WebSocketConfig
package com.epsoft.gas.web.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();
}
}
3:创建websocket服务端
package com.epsoft.gas.major.socket;
/**
* @author lxm
* @date 创建时间:2018年10月11日
*/
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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.ServerEndpoint;
import org.springframework.stereotype.Component;
@ServerEndpoint(value = "/websocket")
@Component
public class CustomWebSocket {
//登录用户名
private String userName;
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<CustomWebSocket>();
//用户名集合
private static Map<String,String> sessionIds = new HashMap<String,String>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) throws Exception {
userName = session.getQueryString();
userName = userName.substring(userName.indexOf("=") + 1);
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount();//在线数加1
System.out.println("用户"+userName+"上线!当前在线人数为" + getOnlineCount());
sessionIds.put(session.getId(), userName);
try {
sendMessage("Hello world");
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);//从set中删除
subOnlineCount();//在线数减1
System.out.println("用户"+userName+"下线!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端"+userName+"的消息:" + message);
//群发消息
for (CustomWebSocket 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 {
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
for (CustomWebSocket item : webSocketSet) {
try {
System.out.println("群发消息:"+message);
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
CustomWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
CustomWebSocket.onlineCount--;
}
}
4:客户端调用
var username = localStorage.getItem("username");
const wsuri = "ws://127.0.0.1:9100/websocket?username="+username;
this.websocket = new WebSocket(wsuri);//这里面的this都指向vue
this.websocket.onopen = this.websocketopen;
this.websocket.onmessage = this.websocketonmessage;
this.websocket.onclose = this.websocketclose;
this.websocket.onerror = this.websocketerror;
websocketopen(){//打开
this.$Message.success({
top: 100,
duration: 3,
content: "WebSocket连接成功!"
});
},
websocketonmessage(e){ //数据接收
if(this.toServer==e.data){
this.productinfos2 = e.data;
}else{
this.productinfos= e.data;
}
},
websocketclose(){ //关闭
this.websocket.close();
},
websocketerror(){ //失败
console.log("WebSocket连接失败");
},
websocketsend(agentData){//数据发送
this.websocket.send(agentData);
// this.productinfos1 = agentData;
},