Home > Java > Java Tutorial > body text

How to use WebSocket+SpringBoot+Vue to build a simple web chat room

WBOY
Release: 2023-05-16 10:46:05
forward
881 people have browsed it

1. Database setup

A very simple user table, add two users admin and wskh

How to use WebSocket+SpringBoot+Vue to build a simple web chat room

2. Backend setup

2.1 Introducing key dependencies
            
    org.springframework.boot            
    spring-boot-starter-websocket       
Copy after login
2.2 WebSocket configuration class

The function of WebSocketConfig is to enable WebSocket monitoring

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/** 
* @Author:WSKH 
* @ClassName:WebSocketConfig 
* @ClassType:配置类 
* @Description:WebSocket配置类 
* @Date:2022/1/25/12:21 
* @Email:1187560563@qq.com 
* @Blog:https://blog.csdn.net/weixin_51545953?type=blog 
*/

@Configuration
public class WebSocketConfig {
    /** * 开启webSocket * @return */ 
    @Bean 
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter(); 
    }
}
Copy after login

WebSocketServer writes some events, such as sending message events , establishing connection events, closing connection events, etc.

import com.wskh.chatroom.util.FastJsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    private static int onlineCount = 0;

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

    private Session session;

    private String sid;


    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.sid = sid;
        this.session = session;
        webSocketServerMap.put(sid, this);
        addOnlineCount();
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        try {
            sendInfo("openSuccess:"+webSocketServerMap.keySet());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose() {
        webSocketServerMap.remove(sid);
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
        try {
            sendInfo("openSuccess:"+webSocketServerMap.keySet());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        if("ping".equals(message)) {
            sendInfo(sid, "pong");
        }
        if(message.contains(":")) {
            String[] split = message.split(":");
            sendInfo(split[0], "receivedMessage:"+sid+":"+split[1]);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        if(error instanceof EOFException) {
            return;
        }
        if(error instanceof IOException && error.getMessage().contains("已建立的连接")) {
            return;
        }
        log.error("发生错误", error);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (session) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    public static void sendObject(Object obj) throws IOException {
        sendInfo(FastJsonUtils.convertObjectToJSON(obj));
    }

    public static void sendInfo(String sid,String message) throws IOException {
        WebSocketServer socketServer = webSocketServerMap.get(sid);
        if(socketServer != null) {
            socketServer.sendMessage(message);
        }
    }

    public static void sendInfo(String message) throws IOException {
        for(String sid : webSocketServerMap.keySet()) {
            webSocketServerMap.get(sid).sendMessage(message);
        }
    }

    public static void sendInfoByUserId(Long userId,Object message) throws IOException {
        for(String sid : webSocketServerMap.keySet()) {
            String[] sids =  sid.split("id");
            if(sids.length == 2) {
                String id = sids[1];
                if(userId.equals(Long.parseLong(id))) {
                    webSocketServerMap.get(sid).sendMessage(FastJsonUtils.convertObjectToJSON(message));
                }
            }
        }
    }

    public static Session getWebSocketSession(String sid) {
        if(webSocketServerMap.containsKey(sid)) {
            return webSocketServerMap.get(sid).session;
        }
        return null;
    }

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

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

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
}
Copy after login
2.3 Configuring cross-domain
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    // 跨域配置
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }

}
Copy after login
2.4 Control class for sending messages
/**
 * @Author:WSKH
 * @ClassName:MsgController
 * @ClassType:控制类
 * @Description:信息控制类
 * @Date:2022/1/25/12:47
 * @Email:1187560563@qq.com
 * @Blog:https://blog.csdn.net/weixin_51545953?type=blog
 */
@ApiModel("信息控制类")
@RestController
@RequestMapping("/chatroom/msg")
public class MsgController {
    @ApiOperation("发送信息方法")
    @PostMapping("/sendMsg")
    public R sendMsg(String msg) throws IOException {
        WebSocketServer.sendInfo(msg);
        return R.ok().message("发送成功");
    }
}
Copy after login

At this point, the back-end part is generally configured.

3. Front-end construction

This article uses the vue-admin-template-master template to build the front-end of the chat room

3.1 Custom file websocket.js

Place the following files in the api folder

How to use WebSocket+SpringBoot+Vue to build a simple web chat room##

//websocket.js
import Vue from 'vue'

// 1、用于保存WebSocket 实例对象
export const WebSocketHandle = undefined

// 2、外部根据具体登录地址实例化WebSocket 然后回传保存WebSocket
export const WebsocketINI = function(websocketinstance) {
  this.WebSocketHandle = websocketinstance
  this.WebSocketHandle.onmessage = OnMessage
}

// 3、为实例化的WebSocket绑定消息接收事件:同时用于回调外部各个vue页面绑定的消息事件
// 主要使用WebSocket.WebSocketOnMsgEvent_CallBack才能访问  this.WebSocketOnMsgEvent_CallBack 无法访问很诡异
const OnMessage = function(msg) {
  // 1、消息打印
  // console.log('收到消息:', msg)

  // 2、如果外部回调函数未绑定 结束操作
  if (!WebSocket.WebSocketOnMsgEvent_CallBack) {
    console.log(WebSocket.WebSocketOnMsgEvent_CallBack)
    return
  }

  // 3、调用外部函数
  WebSocket.WebSocketOnMsgEvent_CallBack(msg)
}

// 4、全局存放外部页面绑定onmessage消息回调函数:注意使用的是var
export const WebSocketOnMsgEvent_CallBack = undefined

// 5、外部通过此绑定方法 来传入的onmessage消息回调函数
export const WebSocketBandMsgReceivedEvent = function(receiveevent) {
  WebSocket.WebSocketOnMsgEvent_CallBack = receiveevent
}

// 6、封装一个直接发送消息的方法:
export const Send = function(msg) {
  if (!this.WebSocketHandle || this.WebSocketHandle.readyState !== 1) {
    // 未创建连接 或者连接断开 无法发送消息
    return
  }
  this.WebSocketHandle.send(msg)// 发送消息
}

// 7、导出配置
const WebSocket = {
  WebSocketHandle,
  WebsocketINI,
  WebSocketBandMsgReceivedEvent,
  Send,
  WebSocketOnMsgEvent_CallBack
}

// 8、全局绑定WebSocket
Vue.prototype.$WebSocket = WebSocket
Copy after login

3.2 Globally introduce websocket in main.js
import '@/utils/websocket' // 全局引入 WebSocket 通讯组件
Copy after login
3.3 Declare the websocket object in App.vue
App.vue



Copy after login

3.4 Chat room interface.vue




Copy after login
3.5 Final effect
Use two different browsers to log in to the admin account and Chat test with wskh account, the effect is as follows (admin is on the left):

How to use WebSocket+SpringBoot+Vue to build a simple web chat room

The above is the detailed content of How to use WebSocket+SpringBoot+Vue to build a simple web chat room. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!