springboot使用webscoket

springboot添加config配置项

复制代码
package cn.lsy.api.yuy.config;

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


@Configuration
public class WebSocketConfig {
    
    // 配置文件
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
    
}

springboot websocket主类

复制代码
package cn.lsy.api.yuy.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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 org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import cn.lsy.api.yuy.entity.Message;

@Component
@ServerEndpoint("/chat/{id}")
public class Websocket {

    private static final Map<String, Session> onLineList = new HashMap<>();

    @OnOpen
    public void OnOpen(Session session, @PathParam("id") String id) {
        // 用户上线
        onLineList.put(id, session);
        // 群发所有人有人上线更新上线列表
        onLineList.forEach((key, value) -> {
            try {
                value.getBasicRemote().sendText(JSON.toJSONString(getOnLine()));
            } catch (IOException e) {
            }
        });
    }

    @OnMessage
    public void onmessage(Session session, String message, @PathParam("id") String id) {
        Message message2 = JSON.parseObject(message,Message.class);
        // 群发所有人
        onLineList.forEach((key, value) -> {
            try {
                value.getBasicRemote().sendText(message2.getContent());
            } catch (IOException e) {
                System.out.println(e);
            }
        });
    }
    public Message getOnLine(){
        ArrayList<String> arrayList = new ArrayList<>();
        Message message = new Message();
        onLineList.forEach((key, value) -> {
            arrayList.add(key);
        });
        message.setOnLinSet(arrayList);
        message.setType("3");
        return message;
    }

    @OnClose
    public void onclose(Session session, @PathParam("id") String id) {
        onLineList.remove(id);
        // 群发所有人有人下线更新在线列表
        onLineList.forEach((key, value) -> {
            try {
                value.getBasicRemote().sendText(JSON.toJSONString(getOnLine()));
            } catch (IOException e) {
                // TODO: handle exception
            }
        });
    }

}

springboot消息实体类

复制代码
package cn.lsy.api.yuy.entity;

import java.util.List;

import lombok.Data;

@Data
public class Message {

    public String type;
    public String content;
    public Integer fromId;
    public Integer toId;
    public List onLinSet;

}

vue

复制代码
<template>
    <div>
      <div>
        <label for="user">用户名:</label>  <input name="user" type="text"  v-model="name">
        <button @click="createWebSocket">加入</button>
      </div>
      <div>
        <label>消息内容:</label><textarea v-model="content"></textarea>
        <button @click="sendMessage">发送</button>
      </div>
      <div>
        当前在线列表
        <div v-for="(item,index) in onLineInfo" :key="index">{{ item }}</div>
        <input type="radio">
      </div>
      <div class="messageBox">
        <div class="q">群聊
          <div>123</div>
        </div>
        <div class="d">单聊
          <div>123</div>
        </div>
      </div>
    </div>
</template>

<script setup>
import { onMounted,ref,reactive} from 'vue';
const name = ref(null);
const content = ref(null);
const toId = ref(null)
const onLineInfo = ref(null)
let ws;

// 建立连接
function createWebSocket(){
    if(name.value!="" && name.value!=null){
        ws = new WebSocket(`ws://localhost:8080/chat/${name.value}`)
        ws.onmessage = message
        ws.onopen = open
    }else{
      alert("用户名不能为空")
    }
 }
function onMessage(e){
  console.log(e)
}
function message(e){
  console.log("message",JSON.parse(e.data))
  const message = JSON.parse(e.data)
  if(message.type === "3"){
    onLineInfo.value = message.onLinSet
  }
}
function open(e){
  console.log("open",e)
}
const sendMessage = ()=>{

  let message = {
    type:1,
    fromId:name.value,
    content:content.value,
    toId:toId.value
  }
  ws.send(JSON.stringify(message))
}

</script>

<style>
.messageBox{
  display: flex;
}
.q,.d{
  width: 200px;
  text-align: center;
}
</style>
相关推荐
.生产的驴4 分钟前
Maven 公司内部私服中央仓库搭建 局域网仓库 资源共享 依赖包构建共享
java·maven
Auc245 分钟前
OJ判题系统第6期之判题逻辑开发——设计思路、实现步骤、代码实现(策略模式)
java·开发语言·docker·容器·策略模式
老李不敲代码10 分钟前
榕壹云搭子系统技术解析:基于Spring Boot+MySQL+UniApp的同城社交平台开发实践
spring boot·mysql·微信小程序·uni-app·软件需求
快乐肚皮13 分钟前
深入解析Docker:核心架构与最佳实践
java·运维·docker·容器
zhou18519 分钟前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
小雅痞1 小时前
[Java][Leetcode middle] 55. 跳跃游戏
java·leetcode
com未来1 小时前
使用 NSSM 安装 Tomcat 11.0.6 为 Windows 服务
java·windows·tomcat
TDengine (老段)1 小时前
基于 TSBS 标准数据集下 TimescaleDB、InfluxDB 与 TDengine 性能对比测试报告
java·大数据·开发语言·数据库·时序数据库·tdengine·iotdb
养军博客1 小时前
spring boot3.0自定义校验注解:文章状态校验示例
java·前端·spring boot
lgily-12251 小时前
常用的设计模式详解
java·后端·python·设计模式