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

这篇具有很好参考价值的文章主要介绍了【WebSocket项目实战】聊天室(前端vue3、后端spring框架)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

1.技术栈

前端:vue3
后端:spring 框架

2.项目实现

1. 前端

1.项目初始化

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

2.项目目录

自动生成的HelloWorld.vue文件可以删除,这里只用创建一个Chat.vue文件【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring

3. 开发页面

项目选择了Ant Design来作为UI框架,直接去Ant Design官网上去拿一个自己看得上的组件即可。Ant Designg官网地址
进入网站后第一件事情是选择一个角色,本项目只提供了三个可选角色分别是
1.精神小伙
【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring
2.美女刺客【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring
3. 屌丝青年
【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring
这里我们通过一个走马灯组件展示角色信息,直接在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>

运行截图
【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring
开发聊天框
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;
      }

    }
  }
}

运行结果
【WebSocket项目实战】聊天室(前端vue3、后端spring框架),websocket,前端,spring

前端完整代码
<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://www.toymoban.com/news/detail-757466.html

到了这里,关于【WebSocket项目实战】聊天室(前端vue3、后端spring框架)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring boot 项目(二十三)——用 Netty+Websocket实现聊天室

    Netty 是基于 Java NIO 的异步事件驱动的网络应用框架,使用 Netty 可以快速开发网络应用,Netty 提供了高层次的抽象来简化 TCP 和 UDP 服务器的编程,但是你仍然可以使用底层的 API。 Netty 的内部实现是很复杂的,但是 Netty 提供了简单易用的API从网络处理代码中解耦业务逻辑。

    2023年04月15日
    浏览(27)
  • 项目介绍:《Online ChatRoom》网页聊天室 — Spring Boot、MyBatis、MySQL和WebSocket的奇妙融合

    在当今数字化社会,即时通讯已成为人们生活中不可或缺的一部分。为了满足这一需求,我开发了一个名为\\\"WeTalk\\\"的聊天室项目,该项目基于Spring Boot、MyBatis、MySQL和WebSocket技术,为用户提供了一个实时交流的平台。在本篇博客中,我将介绍该项目的设计和实现,以及其在社交

    2024年02月11日
    浏览(15)
  • websocket网页聊天室

    实现websocket网页聊天室可以遵循以下步骤: 创建一个基于浏览器的WebSocket客户端,使用JavaScript。可以使用HTML5的WebSocket API。 编写服务器端的WebSocket应用程序,可以使用Node.js和WebSocket模块。 在服务器端创建一个WebSocket服务器,监听客户端请求,并将客户端与服务器端连接起

    2024年02月06日
    浏览(20)
  • Django实现websocket聊天室

    WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器双向通信,即允许服务器主动发送信息给客户端。因此,在WebSocket中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输,客户端和服务器之间的数据交换变

    2023年04月23日
    浏览(20)
  • 【WebSocket】SpringBoot整合WebSocket实现聊天室(一)

    目录 一、准备 1、引入依赖 2、创建配置类 二、相关注解 首先我们需要在项目中引入依赖,有两种方式。第一种我们可以在创建Spring Boot项目时搜索WebSocket然后勾选依赖 第二种是我们可以直接在项目的pom.xml文件中插入以下依赖 我们需要进行如下配置 ServerEndpointExporter 是一个

    2024年02月13日
    浏览(21)
  • 基于WebSocket的在线文字聊天室

    与Ajax不同,WebSocket可以使服务端主动向客户发送响应,本案例就是基于WebSocket的一个在线聊天室,不过功能比较简单,只能满足文字交流。演示如下。 案例学习于b站up主,链接 。这位up主讲的非常清楚,值得去学习。本文属于记录自我学习过程的文章。 项目目录下app.js 项

    2024年02月13日
    浏览(23)
  • django websocket实现聊天室功能

    注意事项channel版本 django2.x 需要匹配安装 channels 2 django3.x 需要匹配安装 channels 3 Django 3.2.4 channels 3.0.3 Django 3.2.* channels 3.0.2 Django4.2 channles==3.0.5 是因为最新版channels默认不带daphne服务器 直接用命令 python manage.py runsever 默认运行的是wsgi ,修改,删除settings中的wsgi,都不能正确运

    2024年01月22日
    浏览(23)
  • Java+Vue实现聊天室(WebSocket进阶-聊天记录)

    WebSocket 是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。 WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服

    2024年02月11日
    浏览(20)
  • 在线聊天室(Vue+Springboot+WebSocket)

    实现了一个简单的在线聊天室的前后端。前端用Vue实现,后端用Springboot实现。         在线聊天室的功能包括创建用户和显示在线用户列表、发送消息和显示消息列表、用户和消息列表实时更新这几点。以下是整体功能的活动图: 用户身份         进入聊天室的用户需

    2024年01月15日
    浏览(17)
  • springboot+websocket实现简单的聊天室

    HTML HTML是创建和构造网页的标准标记语言。它使用一组标记标签描述网页上的内容结构。HTML文档由HTML元素的嵌套结构组成,每个元素由尖括号( )括起的标签表示。这些元素定义了网页的各个部分,如标题、段落、图像、链接、表单等。 JavaScript JavaScript是一种高级、解释性

    2024年01月21日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包