WebSocket实现聊天室功能(springboot+vue3+vite)

1、项目展示图

登录

WebSocket实现聊天室功能(springboot+vue3+vite)_第1张图片

登录成功

WebSocket实现聊天室功能(springboot+vue3+vite)_第2张图片

互动

WebSocket实现聊天室功能(springboot+vue3+vite)_第3张图片

WebSocket实现聊天室功能(springboot+vue3+vite)_第4张图片

2、websocket介绍

websocket是一种全双工的连接,即服务器和客户端之间建立了一次连接后,两者之间就会一直打开这个通道,就可以相互进行通信。相对于传统单双工的http请求,节省很多资源,不需要一直轮询服务器。

3、springboot代码(主要是写websocket相关的方法,比如创建连接事件,接收消息以及发送消息事件,关闭连接事件)

package com.example.message.WebSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gcp.basicproject.util.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Admin
 */
@ServerEndpoint("/chat/{name}")
@Component
public class AllWebSocketService {

    static Logger log = LoggerFactory.getLogger(AllWebSocketService.class);

    private static int onlineCount = 0;

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

    private Session session;

    private String name = "";

    private static ApplicationContext applicationContext;

    /**
     * 解决引入外部类方法
     * @param context
     */
    public static void setApplicationContext(ApplicationContext context){
        applicationContext = context;
    }

    /**
     * 建立连接
     * @param session
     * @param name
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("name") String name){
        this.session = session;
        webSocketServerMap.put(name,this);
        this.name = name;
        addOnlineCount();
        log.info("用户连接:"+name+",当前在线人数为:"+getOnlineCount());
        try{
            sendMessage("进入聊天室成功");
        }catch (IOException e){
            log.error("用户:"+name+",连接失败!!");
        }
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(){
        subOnlineCount();
        webSocketServerMap.remove(name);
        log.info("用户退出:"+name+",当前在线人数为:"+getOnlineCount());
    }


    @OnMessage
    public void onMessage(String message){
        log.info("用户消息:"+name+",报文:"+message);
        if(ParamUtil.notEmpty(message)){
            log.info(message);
            JSONObject jsonObject = JSON.parseObject(message);
            jsonObject.put("name",this.name);
            webSocketServerMap.forEach((u,m)->{
                if(name.contains(u)){
                    return;
                }
                try {
                    m.sendMessage(jsonObject.toJSONString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     * 服务器推送消息
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 获取在线人数
     * @return
     */
    public static  synchronized  int getOnlineCount(){
        return onlineCount;
    }

    /**
     * 上线
     */
    public static  synchronized  void addOnlineCount(){
        AllWebSocketService.onlineCount++;
    }

    /**
     * 离线
     */
    public static  synchronized void subOnlineCount(){
        AllWebSocketService.onlineCount--;
    }

}

4、vue代码(主要是写连接本地的websocket,接收、发送和显示消息)






你可能感兴趣的:(Java,vue3,websocket,spring,boot,java)