Springboot+Vue实现多人聊天室

最近在学习Springboot后端框架,实习的时候有用过Vue.js框架来写过一些前端页面,今天尝试着利用SpringBoot和Vue.js来实现聊天室功能,加深一下理解。

先展示一下做好的效果:

 

 SpringBoot后端代码:

1、新建一个SpringBoot工程

2、首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。这里使用Java注解配置方式,自动配置,配置类代码如下:

 1 package com.example.demospring.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 6 
 7 @Configuration
 8 public class WebScoketConfig {
 9     @Bean
10     public ServerEndpointExporter serverEndpointExporter() {
11         return new ServerEndpointExporter();
12     }
13 }

3、新建一个websocket的具体实现类,代码如下:

 1 package com.example.demospring.controller.WebScoketController;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.bind.annotation.RestController;
 7 import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 8 
 9 import javax.websocket.*;
10 import javax.websocket.server.PathParam;
11 import javax.websocket.server.ServerEndpoint;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.List;
15 @RestController
16 @ServerEndpoint(value="/Room/{username}") // 当创建好一个(服务)端点之后,将它以一个指定的URI发布到应用当中,这样远程客户端就能连接上它了
17 public class WsBytomcate {
18     private static List<Session> sessions = new ArrayList<Session>();
19     @OnOpen
20     public void OnOpen(Session session, @PathParam(value = "username") String username) {
21         sessions.add(session);
22         sendTextMsg("好友 [" + username + "]加入群聊");
23     }
24     @OnMessage
25     public void OnMsg(String msg,@PathParam(value = "username") String username) {
26         sendTextMsg(username + ":" +msg);
27     }
28     @OnClose
29     public void OnClose(Session session, @PathParam("username") String username) throws IOException {
30         sessions.remove(session);
31         sendTextMsg("好友 ["+ username + "] 退出群聊");
32     }
33     @OnError
34     public void OnError(Throwable e) {
35         e.printStackTrace();
36     }
37     private void sendTextMsg(String msg) {
38         for (Session session : sessions) {
39             session.getAsyncRemote().sendText(msg);
40         }
41     }
42 }

Vue.js前端代码:

1、新建vue-cli工程

2、前端页面代码:

<template>
    <div class="roomStyle">
    <br>欢迎使用<strong>VueTest</strong>极简聊天室:<br/><br/>
    <textarea id="content" v-model="content" cols="60" rows="30" readonly="readonly"></textarea><br>
    <input type="text" v-model="message">
    <button type="button" @click="sendMsg()">发送消息</button>
    <br/><br/>
    用户:<input type="text" v-model="user">
    <button @click="joinRoom()">加入群聊</button>
    <button @click="exitRoom()">退出群聊</button>
</div>
</template>
<script>
export default {
  name: 'pageRoom',
  data() {
    return {
      url: 'ws://'+ window.location.host + '/Room/',
      ws: null,
      user: '',
      message: '',
      content: '',
    }
  },
  created(){
  },
  methods: {
    async joinRoom(){
      if(this.ws) {
        alert("你已经再聊天室");
        return;
      }
      let url = this.url;
      let username = this.user;
      this.ws = new WebSocket('ws://127.0.0.1:8080/Room/' + username);  // 后端的启动端口
      this.ws.onopen = this.webscoketonopen;
      this.ws.onmessage =  this.webscoketonmessage;
      //发生错误触发
      this.ws.onerror = function () {
        console.log("连接错误")
      };
      //正常关闭触发
      this.ws.onclose = function () {
        console.log("连接关闭");
      };
    }, 
    webscoketonopen(){
      console.log("与服务器成功建立连接");
    },
    webscoketonmessage(value){
      console.log(value);
      this.content += (value.data + '\r\n') ;
    },
    exitRoom(){
      this.closeWebSocket();
    },
    sendMsg(){
      if(!this.ws) {
        alert('你已经掉线,请重新加入');
        return;
      }
      if(this.ws.readyState === 1){
        this.ws.send(this.message);
        this.message = '';
      } else {
        alert('发送失败');
      }
    },
    closeWebSocket(){
      if(this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    talking(content) {
      console.log(content);
    }
  }
}
</script>
<style>
.roomStyle{
  text-align: center;
  background-color: rgba(15, 161, 230, 0.35);
  margin: 0 auto;
  border: 1px solid #000;
  width: 600px;
  height: 650px
}
</style>

前端源码下载: https://github.com/xxyxt/vueDemo.git

后端源码下载:https://github.com/xxyxt/springdemo.git

参考:https://www.cnblogs.com/chenbenbuyi/p/10779999.html

posted @ 2019-08-28 14:04  下雪不下雨  阅读(2890)  评论(0编辑  收藏  举报