前端vue代码

<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="12" :offset="6">
                <div class="main">
                    <el-row>
                        <el-input
                                placeholder="请输入自己的昵称"
                                prefix-icon="el-icon-user-solid"
                                v-model="name"
                                style="width:50%"
                        ></el-input>
                        <el-button type="primary" @click="conectWebSocket()">建立连接</el-button>
                        <el-button type="danger">断开连接</el-button>
                    </el-row>
                    <el-row>
                        <el-input
                                placeholder="请输入对方频道号"
                                prefix-icon="el-icon-phone"
                                v-model="aisle"
                                style="width:40%"
                        ></el-input>
                    </el-row>
                    <el-row>
                        <el-input
                                placeholder="请输入要发送的消息"
                                prefix-icon="el-icon-s-promotion"
                                v-model="messageValue"
                                style="width:50%"
                        ></el-input>
                        <el-button type="primary" @click="sendMessage()">发送</el-button>
                    </el-row>
                    <div class="message">
                        <div v-for="(value,key,index) in messageList" :key="index">
                            <el-tag v-if="value.name==name" type="success" style="float:right">我:{{value.msg}}</el-tag>
                            <br />
                            <el-tag v-if="value.name!=name" style="float:left">{{value.name}}{{value.msg}}</el-tag>
                            <br />
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                name: "", // 昵称
                websocket: null, // WebSocket对象
                aisle: "", // 对方频道号
                messageList: [], // 消息列表
                messageValue: "" // 消息内容
            };
        },
        methods: {
            conectWebSocket: function() {
                console.log("建立连接");
                if (this.name === "") {
                    this.$alert("请输入自己的昵称", "提示", {
                        confirmButtonText: "确定",
                        callback: action => {}
                    });
                } else {
                    //判断当前浏览器是否支持WebSocket
                    if ("WebSocket" in window) {
                        this.websocket = new WebSocket(
                            "ws://localhost:8888/websocket/" + this.name
                        );
                    } else {
                        alert("不支持建立socket连接");
                    }
                    //连接发生错误的回调方法
                    this.websocket.onerror = function() {

                    };
                    //连接成功建立的回调方法
                    this.websocket.onopen = function(event) {

                    };
                    //接收到消息的回调方法
                    var that = this;
                    this.websocket.onmessage = function(event) {
                        var object = eval("(" + event.data + ")");
                        console.log(object);
                        if (object.type == 0) {
                            // 提示连接成功
                            console.log("连接成功");
                            that.showInfo(object.people, object.aisle);
                        }
                        if (object.type == 1) {
                            //显示消息
                            console.log("接受消息");
                            that.messageList.push(object);
                        }
                    };
                    //连接关闭的回调方法
                    this.websocket.onclose = function() {};
                    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
                    window.onbeforeunload = function() {
                        this.websocket.close();
                    };
                }
            },
            // 发送消息
            sendMessage: function() {
                var socketMsg = { msg: this.messageValue, toUser: this.aisle };
                if (this.aisle == "") {
                    //群聊.
                    socketMsg.type = 0;
                } else {
                    //单聊.
                    socketMsg.type = 1;
                }
                this.websocket.send(JSON.stringify(socketMsg));
            },
            showInfo: function(people, aisle) {
                this.$notify({
                    title: "当前在线人数:" + people,
                    message: "您的频道号:" + aisle,
                    duration: 0
                });
            }
        }
    };
</script>

<style scoped>
    .main {
        position: relative;
        top: 20px;
    }
    .message {
        position: relative;
        overflow:auto;
        top: 20px;
        width: 100%;
        height: 40%;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
        padding: 5px;
    }
</style>

后端Java代码

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.websocket</groupId>
    <artifactId>springboot_websocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_websocket</name>
    <description>实现在线聊天</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--websocket依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <!-- Gson依赖 -->
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-gson</artifactId>
            <version>2.6.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

消息实体类

package com.cyw.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author: CYW
 * @Date: 2021-04-26 10:55
 * @Description: 消息实体
 * @Program: springboot_websocket
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SocketMsg {
    private int type; //聊天类型0:群聊,1:单聊.
    private String fromUser;//发送者.
    private String toUser;//接受者.
    private String msg;//消息
}

WebSocketConfig配置类

package com.cyw.config;

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

/**
 * @Author: CYW
 * @Date: 2021-04-26 10:54
 * @Description:
 * @Program: springboot_websocket
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

webSocket业务逻辑

package com.cyw.service;

import com.cyw.entity.SocketMsg;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;

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

/**
 * @Author: CYW
 * @Date: 2021-04-26 10:57
 * @Description:
 * @Program: springboot_websocket
 * *  使用springboot的唯一区别是要@Component声明,而使用独立容器是由容器自己管理websocket的,
 *  *  但在springboot中连容器都是spring管理的。
 *  *  虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
 *  *  所以可以用一个静态set保存起来
 */
@Component
@ServerEndpoint(value = "/websocket/{nickname}")
public class WebSocketService {
    private String nickname;
    private Session session;
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    //用来记录sessionId和该session进行绑定
    private static Map<String, Session> map = new HashMap<String, Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("nickname") String nickname) {
        Map<String,Object> message=new HashMap<String, Object>();
        this.session = session;
        this.nickname = nickname;
        map.put(session.getId(), session);
        webSocketSet.add(this);//加入set中
        System.out.println("有新连接加入:" + nickname + ",当前在线人数为" + webSocketSet.size());
        //this.session.getAsyncRemote().sendText("恭喜" + nickname + "成功连接上WebSocket(其频道号:" + session.getId() + ")-->当前在线人数为:" + webSocketSet.size());
        message.put("type",0); //消息类型,0-连接成功,1-用户消息
        message.put("people",webSocketSet.size()); //在线人数
        message.put("name",nickname); //昵称
        message.put("aisle",session.getId()); //频道号
        this.session.getAsyncRemote().sendText(new Gson().toJson(message));
    }

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

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("nickname") String nickname) {
        System.out.println("来自客户端的消息-->" + nickname + ": " + message);

        //从客户端传过来的数据是json数据,所以这里使用jackson进行转换为SocketMsg对象,
        // 然后通过socketMsg的type进行判断是单聊还是群聊,进行相应的处理:
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsg socketMsg;

        try {
            socketMsg = objectMapper.readValue(message, SocketMsg.class);
            if (socketMsg.getType() == 1) {
                //单聊.需要找到发送者和接受者.
                socketMsg.setFromUser(session.getId());//发送者.
                Session fromSession = map.get(socketMsg.getFromUser());
                Session toSession = map.get(socketMsg.getToUser());
                //发送给接受者.
                if (toSession != null) {
                    //发送给发送者.
                    Map<String,Object> m=new HashMap<String, Object>();
                    m.put("type",1);
                    m.put("name",nickname);
                    m.put("msg",socketMsg.getMsg());
                    fromSession.getAsyncRemote().sendText(new Gson().toJson(m));
                    toSession.getAsyncRemote().sendText(new Gson().toJson(m));
                } else {
                    //发送给发送者.
                    fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
                }
            } else {
                //群发消息
                broadcast(nickname + ": " + socketMsg.getMsg());
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast(String message) {
        for (WebSocketService item : webSocketSet) {
            item.session.getAsyncRemote().sendText(message);//异步发送消息.
        }
    }

}

结果

请添加图片描述
请添加图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐