自学内容网 自学内容网

【WebSocket项目实战】聊天室(前端vue3、后端spring框架)

最近我学习了WebSocket,为了更好地掌握这一技术,我决定通过做一个项目来巩固学习成果。在这个项目中,我将使用JavaScript和WebSocket来实现实时通信,让客户端和服务器端能够实时地传递和接收数据。通过这个项目,我希望能够更深入地了解WebSocket的工作原理,并且能够在实际应用中灵活运用这一技术。

1.技术栈

前端:vue3
后端:spring 框架

2.项目实现

1. 前端

1.项目初始化

这里使用vue ui 创建vue 项目,具体步骤可以参考这篇文章 Vue ui 初始化项目

2.项目目录

自动生成的HelloWorld.vue文件可以删除,这里只用创建一个Chat.vue文件请添加图片描述

3. 开发页面

项目选择了Ant Design来作为UI框架,直接去Ant Design官网上去拿一个自己看得上的组件即可。Ant Designg官网地址
进入网站后第一件事情是选择一个角色,本项目只提供了三个可选角色分别是
1.精神小伙
请添加图片描述
2.美女刺客请添加图片描述
3. 屌丝青年
请添加图片描述
这里我们通过一个走马灯组件展示角色信息,直接在Ant Designg官网粘贴代码即可

<template>
  <div class="body">
    <div class="character" v-if="isShow">

    <a-carousel class="img" arrows :after-change="onChange">
      <template #prevArrow>
        <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
          <left-circle-outlined/>
        </div>
      </template>
      <template #nextArrow>
        <div class="custom-slick-arrow" style="right: 10px">
          <right-circle-outlined/>
        </div>
      </template>
      <div v-for="(item,i) in characterList" :key="i">
        <img :src="item.url" alt="" mode="scaleToFill">
      </div>
    </a-carousel>

    <div class="choose">
      <button class="btn" @click="setCharcter">选择角色</button>
    </div>

  </div>
  </div>

</template>

<script setup>
import {LeftCircleOutlined, RightCircleOutlined} from '@ant-design/icons-vue';
import {ref, reactive} from 'vue'
import {message} from 'ant-design-vue';
//在线人数
var onlineNum = ref('0')

//在线列表
var onlineList = reactive([])
//是否显示角色框
var isShow = ref(true)
var ws = null;
//角色的id
var id = ref(0)
//角色列表
var characterList = reactive(
    [
      {
        url: require("/public/1.jpg"),
        name: "精神小伙"
      },
      {
        url: require("/public/2.jpeg"),
        name: "美女刺客"
      },
      {
        url: require("/public/3.jpg"),
        name: "屌丝青年"
      }
    ]
)
//切换轮播图后触发
const onChange = (current) => {
  //得到当前轮播图的索引
  id.value = current
};
//设置角色
const setCharcter = () => {
  //选完角色后,要隐藏角色选择框
  isShow.value = false

  //开启webstocket服务的ip地址  ws:// + ip地址 + 访问路径
  ws = new WebSocket('ws://localhost:80/chat/' + id.value);

  //监听是否连接成功
  ws.onopen = function () {
    console.log('ws连接状态:' + ws.readyState)
    if (ws.readyState == 1) {
      message.success('欢迎来到西里网管内部群');
    }
  }
// 接听服务器发回的信息并处理展示
  ws.onmessage = function (data) {

    var res = JSON.parse(data.data);

    console.log(res)
    //type为0表示是系统发送的信息,为 1 时表示时用户发来的信息
    if (res.type == 0) {
      //得到在线人数
      onlineNum.value = res.msg.length
      onlineList = res.msg
    } else {

      var msg = {
        content: "",
        type: '',
        id: ''
      }
      msg.type = '0'
      msg.msg = res.msg
      msg.id = res.id
      msgList.push(msg)
      console.log(res)
    }

  }

  ws.onclose = function () {
    // 监听整个过程中websocket的状态
    console.log('ws连接状态:' + ws.readyState);
    ws.close();
  }
// 监听并处理error事件
  ws.onerror = function (error) {
    console.log(error);
  }
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  window.onbeforeunload = function () {
    ws.close();
  }

}

</script>

<style scoped lang="less">
.body{
   color: #fff;
  font-weight: 900;
  letter-spacing: 2px;
  width: 100%;
  height: 100%;
  background-image: url("/public/5.gif");
  background-size: 50%;
  display: flex;
  align-items: center;
}

.character {
  border-radius: 10px;
  z-index: 10;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, .8);
  width: 300px;
  height: 400px;

  .img {
    width: 200px;
    height: 300px;
    margin: 10px auto;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;

    }
  }
    .btn {
    margin-top: 20px;
    background-color: dodgerblue;
    padding: 10px;
    border: transparent 1px solid;
    border-radius: 3px;
  }


}


:deep(.slick-slide) {
  text-align: center;
  height: 100%;
  line-height: 100%;
  background: #364d79;
  overflow: hidden;
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  transition: ease all 0.3s;
  opacity: 0.3;
  z-index: 1;
}

:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}

:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #fff;
  opacity: 0.5;
}

:deep(.slick-slide h3) {
  color: #fff;
}


</style>

运行截图
在这里插入图片描述
开发聊天框
js 代码


//聊天框
const value = ref('');
const msgList = reactive([])
var sendMessage = (msg) => {
  if (msg.trim() !== '') {
    // 将消息发送到服务器
    ws.send(msg);
  }
}
const onSend = () => {
  sendMessage(value.value)
  var msg = {
    content: "",
    type: '',
    id: ''
  }
  //type为 1代表自己发的消息 type为 0代表别人发的消息
  msg.type = '1'
  msg.msg = value.value
  msgList.push(msg)
  console.log(msgList)
  value.value = ''

};

html

  <div class="container">
      <div class="left">
        <div class="top">
          在线人数
          <Icon type="ios-at-outline"/>
          <span>{{ onlineNum }}人</span>
        </div>
        <div class="list">
          <div class="item" v-for="(item,i) in onlineList" :key="i">
            <img :src="characterList[parseInt(item)].url" alt="" mode="scaleToFill">
            <span>{{ characterList[parseInt(item)].name }}</span>
          </div>

        </div>
      </div>
      <div class="right">
        <div class="top">
          西🍐网管
        </div>
        <div class="chat">
          <div v-for="(item,i) in msgList" :key="i" :class="item.type=='1'?'rightMsg':'leftMsg'">
            <img v-if="item.type=='0'" :src="characterList[parseInt(item.id)].url" alt="">
            <div class="msg">{{ item.msg }}</div>
            <img v-if="item.type=='1'" :src='characterList[parseInt(id)].url' alt="">
          </div>


        </div>
        <div class="bottom">
          <input
              v-model="value"
              placeholder="input  text"
          />
          <button @click="onSend">发送</button>

        </div>
      </div>
    </div>

css

.container {
  z-index: 1;
  border: solid 1px #2c3e50;
  width: 90%;
  height: 95%;
  margin: auto;
  display: flex;
  justify-content: center;

  .left {
    width: 20%;
    height: 100%;
    background-color: rgba(0, 0, 0, .5);

    .top {
      height: 30px;
      border-bottom: solid 1px #2c3e50;
      border-right: solid 1px #2c3e50;
      color: #fff;
      line-height: 30px;
      font-weight: bolder;
    }

    .item {
      height: 70px;
      display: flex;
      flex-direction: row;
      justify-content: start;
      align-items: center;
      width: 100%;

      border-bottom: 1px gray solid;

      img {
        width: 40px;
        height: 40px;
        border-radius: 20px;
        overflow: hidden;
        object-fit: cover;
        margin: 0 10px;

      }

      span {
        font-size: 14px;
        text-align: start;
      }
    }
  }

  .right {
    flex: 1;
    background-color: transparent !important;
    display: flex;
    flex-direction: column;

    .top {
      height: 70px;
      background-color: rgba(0, 0, 0, .5);
      width: 100%;
      font-size: 22px;
      text-align: center;
      line-height: 70px;
    }

    .chat {
      flex: 1;

      .leftMsg,
      .rightMsg {
        display: flex;
        flex-direction: row;
        justify-content: start;
        align-items: center;
        margin: 10px;

        img {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          overflow: hidden;
          object-fit: cover;
          margin: 0 10px;
        }

        .msg {
          display: inline-block;
          padding: 10px;
          word-wrap: anywhere;
          max-width: 500px;
          background-color: #364d79;
          border-radius: 10px;
        }

      }

      .rightMsg {
        justify-content: end;

        .msg {
          color: black;
          background-color: white;
        }
      }
    }

    .bottom {
      height: 100px;
      display: flex;
      align-items: center;
      width: 80%;
      margin: 10px auto;

      input {
        width: 90%;
        border: none;
        outline: none;
        height: 40px;
        color: black;
        text-indent: 2px;
        line-height: 40px;
        border-radius: 10px 0 0 10px;

      }

      button {
        width: 10%;
        border: none;
        outline: none;
        height: 40px;
        line-height: 40px;
        border-radius: 0 10px 10px 0;
        background-color: dodgerblue;
      }

    }
  }
}

运行结果
在这里插入图片描述

前端完整代码
<template>
  <div class="body">
    <div class="container">
      <div class="left">
        <div class="top">
          在线人数
          <Icon type="ios-at-outline"/>
          <span>{{ onlineNum }}人</span>
        </div>
        <div class="list">
          <div class="item" v-for="(item,i) in onlineList" :key="i">
            <img :src="characterList[parseInt(item)].url" alt="" mode="scaleToFill">
            <span>{{ characterList[parseInt(item)].name }}</span>
          </div>

        </div>
      </div>
      <div class="right">
        <div class="top">
          西🍐网管
        </div>
        <div class="chat">
          <div v-for="(item,i) in msgList" :key="i" :class="item.type=='1'?'rightMsg':'leftMsg'">
            <img v-if="item.type=='0'" :src="characterList[parseInt(item.id)].url" alt="">
            <div class="msg">{{ item.msg }}</div>
            <img v-if="item.type=='1'" :src='characterList[parseInt(id)].url' alt="">
          </div>


        </div>
        <div class="bottom">
          <input
              v-model="value"
              placeholder="input  text"
          />
          <button @click="onSend">发送</button>

        </div>
      </div>
    </div>

    <div class="character" v-if="isShow">

      <a-carousel class="img" arrows :after-change="onChange">
        <template #prevArrow>
          <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
            <left-circle-outlined/>
          </div>
        </template>
        <template #nextArrow>
          <div class="custom-slick-arrow" style="right: 10px">
            <right-circle-outlined/>
          </div>
        </template>
        <div v-for="(item,i) in characterList" :key="i">
          <img :src="item.url" alt="" mode="scaleToFill">
        </div>
      </a-carousel>

      <div class="choose">
        <button class="btn" @click="setCharcter">选择角色</button>
      </div>

    </div>
  </div>

</template>

<script setup>
import {LeftCircleOutlined, RightCircleOutlined} from '@ant-design/icons-vue';
import {ref, reactive} from 'vue'
import {message} from 'ant-design-vue';
//在线人数
var onlineNum = ref('0')

//在线列表
var onlineList = reactive([])
//是否显示角色框
var isShow = ref(true)
var ws = null;
//角色的id
var id = ref(0)
//角色列表
var characterList = reactive(
    [
      {
        url: require("/public/1.jpg"),
        name: "精神小伙"
      },
      {
        url: require("/public/2.jpeg"),
        name: "美女刺客"
      },
      {
        url: require("/public/3.jpg"),
        name: "屌丝青年"
      }
    ]
)
//切换轮播图后触发
const onChange = (current) => {
  //得到当前轮播图的索引
  id.value = current
};
//设置角色
const setCharcter = () => {
  //选完角色后,要隐藏角色选择框
  isShow.value = false

  //开启webstocket服务的ip地址  ws:// + ip地址 + 访问路径
  ws = new WebSocket('ws://localhost:80/chat/' + id.value);

  //监听是否连接成功
  ws.onopen = function () {
    console.log('ws连接状态:' + ws.readyState)
    if (ws.readyState == 1) {
      message.success('欢迎来到西里网管内部群');
    }
  }
// 接听服务器发回的信息并处理展示
  ws.onmessage = function (data) {

    var res = JSON.parse(data.data);

    console.log(res)
    //type为0表示是系统发送的信息,为 1 时表示时用户发来的信息
    if (res.type == 0) {
      //得到在线人数
      onlineNum.value = res.msg.length
      onlineList = res.msg
    } else {

      var msg = {
        content: "",
        type: '',
        id: ''
      }
      msg.type = '0'
      msg.msg = res.msg
      msg.id = res.id
      msgList.push(msg)
      console.log(res)
    }

  }

  ws.onclose = function () {
    // 监听整个过程中websocket的状态
    console.log('ws连接状态:' + ws.readyState);
    ws.close();
  }
// 监听并处理error事件
  ws.onerror = function (error) {
    console.log(error);
  }
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  window.onbeforeunload = function () {
    ws.close();
  }

}

//聊天框
const value = ref('');
const msgList = reactive([])
var sendMessage = (msg) => {
  if (msg.trim() !== '') {
    // 将消息发送到服务器
    ws.send(msg);
  }
}
const onSend = () => {
  sendMessage(value.value)
  var msg = {
    content: "",
    type: '',
    id: ''
  }
  //type为 1代表自己发的消息 type为 0代表别人发的消息
  msg.type = '1'
  msg.msg = value.value
  msgList.push(msg)
  console.log(msgList)
  value.value = ''

};

</script>

<style scoped lang="less">
.body {
  color: #fff;
  font-weight: 900;
  letter-spacing: 2px;
  width: 100%;
  height: 100%;
  background-image: url("/public/5.gif");
  background-size: 50%;
  display: flex;
  align-items: center;
  position: relative;
}

.character {
  border-radius: 10px;
  z-index: 10;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, .8);
  width: 300px;
  height: 400px;

  .img {
    width: 200px;
    height: 300px;
    margin: 10px auto;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;

    }
  }

  .btn {
    margin-top: 20px;
    background-color: dodgerblue;
    padding: 10px;
    border: transparent 1px solid;
    border-radius: 3px;
  }


}

.body {
  :deep(.slick-slide) {
    text-align: center;
    height: 100%;
    line-height: 100%;
    background: #364d79;
    overflow: hidden;
  }

  :deep(.slick-arrow.custom-slick-arrow) {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: #fff;
    background-color: rgba(31, 45, 61, 0.11);
    transition: ease all 0.3s;
    opacity: 0.3;
    z-index: 1;
  }

  :deep(.slick-arrow.custom-slick-arrow:before) {
    display: none;
  }

  :deep(.slick-arrow.custom-slick-arrow:hover) {
    color: #fff;
    opacity: 0.5;
  }

  :deep(.slick-slide h3) {
    color: #fff;
  }

}

.container {
  z-index: 1;
  border: solid 1px #2c3e50;
  width: 90%;
  height: 95%;
  margin: auto;
  display: flex;
  justify-content: center;

  .left {
    width: 20%;
    height: 100%;
    background-color: rgba(0, 0, 0, .5);

    .top {
      height: 30px;
      border-bottom: solid 1px #2c3e50;
      border-right: solid 1px #2c3e50;
      color: #fff;
      line-height: 30px;
      font-weight: bolder;
    }

    .item {
      height: 70px;
      display: flex;
      flex-direction: row;
      justify-content: start;
      align-items: center;
      width: 100%;

      border-bottom: 1px gray solid;

      img {
        width: 40px;
        height: 40px;
        border-radius: 20px;
        overflow: hidden;
        object-fit: cover;
        margin: 0 10px;

      }

      span {
        font-size: 14px;
        text-align: start;
      }
    }
  }

  .right {
    flex: 1;
    background-color: transparent !important;
    display: flex;
    flex-direction: column;

    .top {
      height: 70px;
      background-color: rgba(0, 0, 0, .5);
      width: 100%;
      font-size: 22px;
      text-align: center;
      line-height: 70px;
    }

    .chat {
      flex: 1;

      .leftMsg,
      .rightMsg {
        display: flex;
        flex-direction: row;
        justify-content: start;
        align-items: center;
        margin: 10px;

        img {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          overflow: hidden;
          object-fit: cover;
          margin: 0 10px;
        }

        .msg {
          display: inline-block;
          padding: 10px;
          word-wrap: anywhere;
          max-width: 500px;
          background-color: #364d79;
          border-radius: 10px;
        }

      }

      .rightMsg {
        justify-content: end;

        .msg {
          color: black;
          background-color: white;
        }
      }
    }

    .bottom {
      height: 100px;
      display: flex;
      align-items: center;
      width: 80%;
      margin: 10px auto;

      input {
        width: 90%;
        border: none;
        outline: none;
        height: 40px;
        color: black;
        text-indent: 2px;
        line-height: 40px;
        border-radius: 10px 0 0 10px;

      }

      button {
        width: 10%;
        border: none;
        outline: none;
        height: 40px;
        line-height: 40px;
        border-radius: 0 10px 10px 0;
        background-color: dodgerblue;
      }

    }
  }
}


</style>

2. 后端部分

  1. 导入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

3). 定义WebSocket服务端组件

package com.example.chat;

/**
 * @author 余炜
 * @version 1.0
 */

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
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.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/chat/{id}")
@Component
@Slf4j
public class Websocket {

    //记录连接的客户端
    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    //0:连接成功系统发送信息 1:用户发送的消息
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {

        clients.put(id, session);
        //获取在线用户的id
        List<String> onlineList = new ArrayList<>();
        for (String key : clients.keySet()) {
            onlineList.add(key);
        }
        Websocket.sendMessage(new response<List<String>>(0, id, onlineList), session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("id") String id) {
        log.info(id + "连接断开!");
        clients.remove(id);
    }

    /**
     * 判断是否连接的方法
     *
     * @return
     */
    public static boolean isServerClose() {
        if (Websocket.clients.values().size() == 0) {
            log.info("已断开");
            return true;
        } else {
            log.info("已连接");
            return false;
        }
    }


    /**
     * 发送给所有用户
     *
     * @param
     */
    public static void sendMessage(response response, Session session) {
        String message = JSONObject.toJSONString(response);
        for (Session session1 : Websocket.clients.values()) {
            try {
                 //判断一下是不是系统发送的信息,和是不是自己发送的信息
                if (response.getType() == 0 || !session.equals(session1))
                    session1.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     * @param session
     */

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("id") String id) {

        sendMessage(new response<String>(1, id, message), session);


    }

    /**
     * 发生错误时的回调函数
     *
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.info("错误");
        error.printStackTrace();
    }

}

4). 定义配置类,注册WebSocket的服务端组件

package com.example.chat.config;

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

/**
 * @author 余炜
 * @version 1.0
 */

/**
 * 开启WebSocket支持
 */
@Configuration
public class webSocketConfig {
   @Bean
   public ServerEndpointExporter serverEndpointExporter() {
      return new ServerEndpointExporter();
   }
}

封装一个回复实体类

package com.example.chat;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author 余炜
 * @version 1.0
 */
@Data
@AllArgsConstructor
public class response<T> {
   private int type;

   private String id;

   private  T msg;


}

结语

本次项目实战分享到此圆满结速,希望能对那些正在探索或已经踏入WebSocket领域的读者们有所帮助。我希望这篇博客能激发你的兴趣,让你对WebSocket有更深的理解,同时也希望你能在评论区分享你的经验和观点,让我们一起学习,一起进步。再次感谢你阅读我的博客,期待你的反馈和参与!让我们一起在学习的道路上一起前行,共同探索技术的无尽可能。


原文地址:https://blog.csdn.net/weixin_55939638/article/details/134491416

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!