websocket的依赖jar包_websocket的简单使用

1、maven项目,第一步需要配置jar包

org.springframework.boot

spring-boot-starter-websocket

2、前台使用

var websocket = null;

//判断当前浏览器是否支持WebSocket

if('WebSocket' in window){

//连接WebSocket节点

websocket = new WebSocket("ws://localhost:81/api/imserver/"+用户id;);

}else{

console.log("您的浏览器不支持WebSocket");

}

//连接发生错误的回调方法

websocket.onerror = function(){

};

//连接成功建立的回调方法

websocket.onopen = function(event){

}

//接收到消息的回调方法

websocket.onmessage = function(event){

setMessageInnerHTML(event.data);

}

//连接关闭的回调方法

websocket.onclose = function(){

}

//发送消息

function send(){

var message = document.getElementById('text').value;

websocket.send(message);

}

窗口关闭或者退出登录时调用,如果挂掉需要重新请求

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。

window.onbeforeunload = function(){

websocket.close();

}

前台检测后台是否挂掉

//针对断网的情况的心跳重连

var heartCheck = {

timeout: 20000,//20ms

timeoutObj: null,

reset: function( ){

clearTimeout(this.timeoutObj);

  this.start();

},

start: function( ){

this.timeoutObj = setTimeout(function(){

websocket.send("HeartBeat"); //自定义需要执行的命令

}, this.timeout)

}

};

heartCheck.start();

heartCheck.reset();

//将消息显示在网页上

function setMessageInnerHTML(innerHTML){

document.getElementById('message').innerHTML += innerHTML + '
';

}

3、后台使用

新建WebSocketConfig 类

@Configuration

public class WebSocketConfig {

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

新建WebSocketServer类

@ServerEndpoint(value="/imserver/{userId}")

@Component

public class WebSocketServer {

private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/

private static int onlineCount = 0;

/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/

private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();

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

private Session session;

/**接收userId*/

private String userId="";

/**

* 连接建立成功调用的方法

**/

@OnOpen

public void onOpen(Session session,@PathParam("userId") String userId) {

this.session = session;

this.userId=userId;

if(webSocketMap.containsKey(userId)){

webSocketMap.remove(userId);

webSocketMap.put(userId,this);

//加入set中

}else{

webSocketMap.put(userId,this);

//加入set中

addOnlineCount();

//在线数加1

}

log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

try {

sendMessage("");

} catch (IOException e) {

log.error("用户:"+userId+",网络异常!!!!!!");

}

}

/**

* 连接关闭调用的方法

*/

@OnClose

public void onClose() {

if(webSocketMap.containsKey(userId)){

webSocketMap.remove(userId);

//从set中删除

subOnlineCount();

}

log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());

}

/**

* 收到客户端消息后调用的方法

*

* @param message 客户端发送过来的消息*/

@OnMessage

public void onMessage(String message, Session session) {

//log.info("用户消息:"+userId+",报文:"+message);

//可以群发消息

//消息保存到数据库、redis

if(StringUtils.isNotBlank(message)){

try {

if("ping".equals(message)) {

webSocketMap.get(userId).sendMessage("pong");

}else {

//解析发送的报文

JSONObject jsonObject = JSON.parseObject(message);

//追加发送人(防止串改)

jsonObject.put("fromUserId",this.userId);

String toUserId=jsonObject.getString("toUserId");

//传送给对应toUserId用户的websocket

if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){

webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());

}else{

log.error("请求的userId:"+toUserId+"不在该服务器上");

//否则不在这个服务器上,发送到mysql或者redis

}

}

}catch (Exception e){

e.printStackTrace();

}

}

}

/**

* 用户错误

* @param session

* @param error

*/

@OnError

public void onError(Session session, Throwable error) {

log.error("用户错误:"+this.userId+",原因:"+error.getMessage());

}

/**

* 实现服务器主动推送

*/

public void sendMessage(String message) throws IOException {

this.session.getBasicRemote().sendText(message);

}

/**

* 发送自定义消息

* */

public static void sendInfo(String message,@PathParam("userId") String userId) {

try {

log.info("发送消息到:"+userId+",报文:"+message);

if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){

webSocketMap.get(userId).sendMessage(message);

}else{

log.error("用户"+userId+",不在线!");

}

} catch (Exception e) {

log.error("异常"+userId+",报文:"+message);

}

}

public static synchronized int getOnlineCount() {

return onlineCount;

}

public static synchronized void addOnlineCount() {

WebSocketServer.onlineCount++;

}

public static synchronized void subOnlineCount() {

WebSocketServer.onlineCount--;

}

}

后台使用时调用其发送方法,前台就可以收到,然后修改页面显示

WebSocketServer.sendInfo("",userid);

谢谢观看!!!

ea6352b592e3df1ad2c96c200e717132.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值