由于项目需求管理员这边发通知需要主动通知到用户,所以决定采用websocket方式进行前后端数据交换,后来便决定一个页面的所有请求全部用websocket,因此需要json格式来包装键值对的请求名和请求内容。
奉上springboot内置tomcat的websocket配置及使用。

1:Config配置,目前看到说是内置springboot需要注入beanServerEndpointExporter,待我们项目部署到外置tomcat服务器时删除,不需要注入
在这里插入图片描述

2:WebSocketController实现

在这里插入图片描述
贴上代码吧`
package com.ctfplatform.hznuctf.controller;

import com.ctfplatform.hznuctf.dao.CompetitionDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = “/websocket”)
@Component
public class WebSocketController {

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

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

/**
 * 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
    this.session = session;
    webSocketSet.add(this);     //加入set中
    addOnlineCount();           //在线数加1
    System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    try {
        sendMessage("conpetitionList","123");
    } catch (IOException e) {
        System.out.println("websocket IO异常");
    }
}
//	//连接打开时执行
//	@OnOpen
//	public void onOpen(@PathParam("user") String user, Session session) {
//		currentUser = user;
//		System.out.println("Connected ... " + session.getId());
//	}

/**
 * 连接关闭调用的方法
 */
@OnClose
public void onClose() {
    webSocketSet.remove(this);  //从set中删除
    subOnlineCount();           //在线数减1
    System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}

/**
 * 收到客户端消息后调用的方法
 *
 * @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session){
    System.out.println(message);
    JSONObject jo = JSONObject.fromObject(message);
    System.out.println(jo);
    JSONObject jo2 = JSONObject.fromObject(jo.get("submit"));
    System.out.println(jo2.get("competitionId"));
    System.out.println("来自客户端的消息:" + message);

// 群发消息
for (WebSocketController item : webSocketSet) {
try {
item.sendMessage(“conpetitionList”,“111”);
item.sendMessage(“questionList”,“222”);
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
 *
 * @param session
 * @param error
 */
@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);
// }

public void sendMessage(String message,Object datas) throws IOException {
    JSONObject result = new JSONObject();
    result.put("message", message);
    result.put("datas", datas);
    this.session.getBasicRemote().sendText(result.toString());
}

/**
 * 群发自定义消息
 * */
public static void sendInfo(String message) throws IOException {
    System.out.println(message);
    for (WebSocketController item : webSocketSet) {
        try {
            item.sendMessage("conpetitionList",message);
        } catch (IOException e) {
            continue;
        }
    }
}

public static synchronized int getOnlineCount() {
    return onlineCount;
}

public static synchronized void addOnlineCount() {
    WebSocketController.onlineCount++;
}

public static synchronized void subOnlineCount() {
    WebSocketController.onlineCount--;
}

}
`
其中最主要的便是sendMessage方法,可以自定义方法,最后将json格式转成字符串传输即可。

而在onMessage里接到前端传递过来的json对象字符串形式后,需要通过
JSONObject.fromObject。这个包通过maven引入。

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

jdk版本必须是这个才不报错噢
总之websocket还是比较简单的 ,又能实现实时的数据传输 很不错。

Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐