社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
由于新建的项目,pom中少写了几行配置,导致代码中找不到ServerEndpointExporter类,pom少写的配置:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
WebSocketConfig.java
package com.becom.qoe.wsservice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
* This class is used for ...
* @author leiqianpeng
* 2019年4月15日 下午4:36:22
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer.java
package com.becom.qoe.wsservice.server;
import java.io.IOException;
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.springframework.stereotype.Component;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log=LogFactory.getLog(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
EmReturnCode.java
package com.becom.qoe.wsservice.entity;
/**
* 接口返回代码 枚举
*/
public enum EmReturnCode {
SUCCESS("成功",1),
FAIL("失败",-1);
// 成员变量
private String name;
private int value;
// 构造方法
private EmReturnCode(String name, int value) {
this.name = name;
this.value = value;
}
// 普通方法
public static String getName(int value) {
for (EmReturnCode c : EmReturnCode.values()) {
if (c.getValue() == value) {
return c.name;
}
}
return null;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
ReturnJson.java
package com.becom.qoe.wsservice.entity;
import java.io.Serializable;
public class ReturnJson implements Serializable{
private static final long serialVersionUID = 1L;
private String msg;
private int retcode;
private Object retObj;
private boolean success;
public final static ReturnJson Success = new ReturnJson("操作成功", EmReturnCode.SUCCESS.getValue(), null,true);
public final static ReturnJson Faild = new ReturnJson("操作失败", EmReturnCode.FAIL.getValue(), null,false);
public ReturnJson(String msg, int retcode, Object retObj,boolean success) {
super();
this.msg = msg;
this.retcode = retcode;
this.retObj = retObj;
this.success = success;
}
public ReturnJson(String msg, Object retObj) {
super();
this.msg = msg;
this.retcode = EmReturnCode.SUCCESS.getValue();
this.retObj = retObj;
this.success = true;
}
public ReturnJson(String msg,boolean success) {
super();
this.msg = msg;
this.retcode = EmReturnCode.SUCCESS.getValue();
this.retObj = null;
this.success = success;
}
public String getMsg() {
return msg;
}
public int getRetcode() {
return retcode;
}
public Object getRetObj() {
return retObj;
}
public boolean isSuccess() {
return success;
}
public static ReturnJson getSuccess() {
return Success;
}
public static ReturnJson getFaild() {
return Faild;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setRetcode(int retcode) {
this.retcode = retcode;
}
public void setRetObj(Object retObj) {
this.retObj = retObj;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
CheckCenterController
package com.becom.qoe.wsservice.controller;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.becom.qoe.wsservice.entity.ReturnJson;
import com.becom.qoe.wsservice.server.WebSocketServer;
@Controller
@RequestMapping("/checkcenter")
public class CheckCenterController {
//页面请求
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav=new ModelAndView("/socket");
mav.addObject("cid", cid);
return mav;
}
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public ReturnJson pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return ReturnJson.Faild;
}
return ReturnJson.Success;
}
}
前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://172.16.16.199:8771/websocket/20");
//socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
1.打开上面写的前端页面:
2.使用postman推送消息:
3.返回浏览器,可查看到浏览器已经接收到消息了
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!