您的位置:首页 > 编程语言 > Java开发

spring boot 集成webSocket 实现前后端数据实时交互

2019-01-10 15:27 573 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hzd0727/article/details/86234492

1.引入包

gradle:

compile "org.springframework.boot:spring-boot-starter-websocket"

2.服务端代码

@Slf4j
@ServerEndpoint(value = "/websocket")
@Component
@EnableWebSocket
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private final int maxLine = 300;

/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session se
4000
ssion) {
this.session = session;
webSocketSet.add(this);     //加入set中
addOnlineCount();           //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功"+ "</br>");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
//    //连接打开时执行
//    @OnOpen
//    public void onOpen(@PathParam("businessId") Long businessId,
//                       @PathParam("cmd") String cmd,
//                       Session session) {
//        webSocketSet.add(this);     //加入set中
//        addOnlineCount();           //在线数加1
//        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
//
//    }

/**
* 连接关闭调用的方法
*/
@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("来自客户端的消息:" + message);

             //处理逻辑返回前端

sendMessage(message);
}

/**
*
* @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) throws IOException {
log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
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--;
}
}

3.前端

</div>
<table class="layui-table">
<div class="conWrap">
<div id="log-container" style="height: 450px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;">
<div></div>
</div>
</div>
</table>

 

4.js

var websocket = null;

//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
// websocket = new WebSocket("ws://localhost:1234/websocket");
websocket = new WebSocket("ws://10.8.16.25:1234/websocket");
}
else{
alert('Not support websocket')
}

//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error"+ "</br>");
};

//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open"+ "</br>");
}

//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}

//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close"+ "</br>");
}

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
$("#log-container div").append(innerHTML);
// 滚动条滚动到最低部
$("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
}

//关闭连接
function closeWebSocket(){
websocket.close();
}

//发送消息到服务端
function sendMessage(){
var message = "";//传达参数消息
websocket.send(message);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: