SpringBoot+Vue+WebSocket打造在线聊天室

这只是一个小雏形,通过websocket实现了前后端的即时通信,后续会做一个精美的在线聊天室,届时欢迎大家指教

聊天室架构图

@OnError改成@OnClose

SpringBoot+Vue+WebSocket打造在线聊天室_第1张图片

聊天室开发文档

# 客户端发消息到服务器
	{"fromName":"张三","toName":"李四","message":"你好"}
# 服务端到客户端
	1、系统轮播消息
	{"isSystem":true,"fromName":null,"toName":null,"message":["李四","王五"]}
	2、发送某人的消息发送给某人
	{"isSystem":false,"fromName":"张三","toName":"李四","message":["李四","王五"]}

聊天室前端代码


<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>WebSocket测试title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
    //添加js使得websocket不会自动关闭
	<script src="https://cdn.bootcss.com/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js">script>
head>
<body>

<div id="app">
    <div id="left">
        <h4 id="new">h4>
        <div id="content">

        div>
        <div id="input">
            <input type="text" v-model="text" id="input_text" @keyup.enter="send">
            <button  id="submit" v-on:click="send">发送button>
        div>
        <div id="receive" > {{ receive }} div>
    div>
div>

body>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            server: "ws://127.0.0.1:8080/chat_server",
            socket: null,
        },
        methods: {
            //初始化websocket
            initConn() {
                let socket = new WebSocket(this.server);//创建Socket实例
                this.socket = socket
                this.socket.onmessage = this.OnMessage;
                this.socket.onopen = this.OnOpen;
            },
            OnOpen() {
                let mes = {}
                mes.type = "test";
                this.socket.send(JSON.stringify(mes));
            },
            OnMessage(e) {
                const redata = JSON.parse(e.data);
                console.log(redata)
            },


        },
        created: function () {
            this.initConn();
        }
    })
script>
html>

创建配置类

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

@Configuration
public class WebsocketConfig {
    public class WebSocketConfig {
        /**
         * ServerEndpointExporter 作用
         * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
         * @return
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
}

后端websocket类

package com.example.ems.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author zrl
 * @date 2020-12-23 15:23
 */
@Component
@ServerEndpoint("/chat")
@Slf4j
public class Websocket {
    private Session session;
    //    存储websocket
    private static CopyOnWriteArraySet<Websocket> webSocketSet = new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("有新的客户端连接,当前总数为:{}",webSocketSet.size());
    }
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("客户端关闭,当前总数为:{}",webSocketSet.size());
    }
    @OnMessage
    public void onMessage(String message) {
        log.info("【收到消息:{}】",message);
        sendMessage(message);
    }
    public void sendMessage(String message) {
        for(Websocket websocket:webSocketSet) {
            log.info("【websocket广播消息,message={}】",message);
            try {
                websocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

你可能感兴趣的:(Spring,Boot小白成长之路,websocket,vue,网络通信,spring,boot,socket)