实现点击用户头像或者id与其用户进行聊天(vue+springboot+WebSocket)

用户点击id直接与另一位用户聊天

前端如此:

<template>
  <!-- 消息盒子 -->
  <div class="content-box" :style="contentWidth">
    <!-- 头像,用户名 -->
    <div class="content-box-top box--flex">
      <el-avatar
        class="content-box-avatar"
        shape="circle"
        :size="50"
        :src="handleCampusUrl(contentObj.params.avatar)"
      ></el-avatar>
      <div
        class="box--flex"
        style="height: 100%; justify-content: center; flex-direction: column"
      >
        <div class="box--flex" style="margin-bottom: 7px; font-weight: bolder">
          <span class="nickName" @click="handleClickNickName">
            {{ contentObj.params.nickName }}
          </span>
        </div>
        <div class="box--flex">
          <div class="content-category-tag">
            <div>{{ contentObj.params.categoryName }}</div>
          </div>
          <span class="content-box-time">
            {{ parseTime(contentObj.createTime, "{y}-{m}-{d} {h}:{i}") }}
          </span>
        </div>
      </div>
    </div>
    <!-- 内容 -->
    <div
      class="content-feed-content"
      style="padding-left: 60px; margin: 0px 10px 0 0"
    >
      <div class="content-feed-ogText">
        <!-- 文字 -->
        <div style="white-space: pre-wrap">{{ contentObj.content }}</div>
      </div>
      <!-- 信息墙的图片/视频 -->
      <div style="margin-top: 10px">
        <ContentFile
          v-if="contentObj.type != 0"
          :fileUrls="contentObj.fileUrl"
          :contentType="contentObj.type"
        ></ContentFile>
      </div>
    </div>

    <!-- 信息墙底部 -->
    <ContentBottom
      :zanBoolean="zanBoolean"
      :contentObj="contentObj"
    ></ContentBottom>
  </div>
</template>

<script>
//组件
import ContentBottom from "@/components/ContentBottom";
import ContentFile from "@/components/ContentFile";

import { getToken, setToken, removeToken } from "@/utils/auth";

export default {
  name: "Content",
  props: ["contentObj", "loveContentIds"],
  //import引入的组件需要注入到对象中才能使用
  components: { ContentBottom, ContentFile },
  data() {
    //这里存放数据
    return {
      //是否点赞
      zanBoolean: false,
      contentWidth: "width:605px;",
    };
  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
    let width = document.documentElement.clientWidth;
    if (width < 642) {
      this.contentWidth = "";
    }
    this.isZan(this.contentObj.contentId);
  },
  watch: {
    contentObj: {
      handler(newVal, oldVal) {
        // console.log(newVal);
        this.isZan(newVal.contentId);
      },
      deep: true,
      immediate: true,
    },
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  //方法集合
  methods: {
    //判断是否被点赞
    isZan(contentId) {
      if (this.loveContentIds.indexOf(contentId) == -1) {
        this.zanBoolean = false;
      } else {
        this.zanBoolean = true;
      }
    },
    handleClickNickName() {
      // 输出nickName到控制台
      console.log("输出的用户名=",this.contentObj.params.nickName);
      // 路由跳转,并传递参数
      this.$router.push({ name: 'chat', params: { nickName: this.contentObj.params.nickName } });
    },
  },
};
</script>
<style>
.content-box {
  /* box-shadow: 0 10px 12px 0 rgba(0, 0, 0, 0.2); */
  margin: 0 0 20px 0;
  padding: 20px 20px 0;
  background-color: #fff;
  box-shadow: 0px 0px 25px rgb(0 0 0 / 10%);
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 10px;
}
.box--flex {
  display: flex;
}
.content-box-top {
  height: 50px;
}
.content-feed-ogText {
  color: #333;
  font-size: 14px;
  line-height: 24px;
}
.content-footer {
  height: 40px;
  line-height: 40px;
  margin: 0 15px;
}
.nickName {
  font-size: 15px;
  font-weight: bold;
}
.content-box-time {
  font-size: 12px;
  color: darkgrey;
}
.content-category-tag {
  margin-right: 4px;
  font-size: 12px;
  display: inline-block;
  min-width: 26px;
  height: 13px;
  border: 1px solid #ccc;
  border-radius: 2px;
  line-height: 13px;
  color: #939393;
  text-align: center;
}

.content-box-avatar {
  margin-right: 10px;
}
</style>
<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <el-row>
      <el-col :span="20">
        <div style="width: 800px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
          <div style="text-align: center; line-height: 50px;">
            聊天--{{ chatUser }}
          </div>
          <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
          <div style="height: 200px">
            <textarea v-model="text" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none"></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import request from "@/utils/request";
let socket;
import userInfoApi from "@/api/userInfo";
export default {
  name: "Im",
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      isCollapse: false,
      users: [],
      chatUser: '',
      text: "",
      messages: [],
      content: ''
    }
  },
  created() {
    //另一个页面传过来的 对话人 
    this.chatUser = this.$route.params.nickName;
    console.log("传入的this.chatUser=",this.chatUser)
    this.init(); // 初始化 WebSocket 连接
    // this.chatUser = 'ruan';
    this.text = ''; // 清空输入框内容
    this.send(); // 发送消息给张三
  },
  methods: {
    getUser() {
      userInfoApi.getUserProfile().then((response) => {
        console.log("response========",response)
        this.user = {"username": response.data.userName};
      });
    },
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {from: this.user.username, to: this.chatUser, text: this.text}
          socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端,由服务端进行转发
          this.messages.push({user: this.user.username, text: this.text})
          // 构建消息内容,本人消息
          this.createContent(null, this.user.username, this.text)
          this.text = '';
        }
      }
    },
    createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息,绿色气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
          "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
          "    <div class=\"tip left\">" + text + "</div>\n" +
          "  </div>\n" +
          "  <div class=\"el-col el-col-2\">\n" +
          "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
          "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
          "  </span>\n" +
          "  </div>\n" +
          "</div>";
      } else if (remoteUser) {   // remoteUser表示远程用户聊天消息,蓝色的气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
          "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
          "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
          "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
          "  </span>\n" +
          "  </div>\n" +
          "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
          "    <div class=\"tip right\">" + text + "</div>\n" +
          "  </div>\n" +
          "</div>";
      }
      console.log(html)
      this.content += html;
    },
    init() {

      this.getUser();
      console.log("拿到的user=",this.user)

      let username = this.user.username;

      // this.user = {"username": "张三"}
      userInfoApi.getUserProfile().then((response) => {
        console.log("response========",response)
        username =  response.data.userName;

        console.log("this.user.username===",this.user.username)

        let _this = this;
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          // console.log("您的浏览器支持WebSocket");
          let socketUrl = "ws://localhost:8160/imserver/" + username;
          if (socket != null) {
            socket.close();
            socket = null;
          }
          // 开启一个websocket服务
          socket = new WebSocket(socketUrl);
          //打开事件
          socket.onopen = function () {
            // console.log("websocket已打开");
          };
          //  浏览器端收消息,获得从服务端发送过来的文本消息
          socket.onmessage = function (msg) {
            console.log("收到数据====" + msg.data)
            let data = JSON.parse(msg.data)  // 对收到的json数据进行解析, 类似这样的: {"users": [{"username": "zhang"},{ "username": "admin"}]}
            // console.log(data)
            if (data.users) {  // 获取在线人员信息
              _this.users = data.users.filter(user => user.username !== username)  // 获取当前连接的所有用户信息,并且排除自身,自己不会出现在自己的聊天列表里
              // console.log(_this.users)
            } else {
              if (data.from === _this.chatUser) {
                _this.messages.push(data)
                _this.createContent(data.from, null, data.text)
              }
            }
          };
          //关闭事件
          socket.onclose = function () {
            console.log("websocket已关闭");
          };
          //发生了错误事件
          socket.onerror = function () {
            console.log("websocket发生了错误");
          }
        }




      });



    }
  }
}
</script>
<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}
.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>

前端完毕,然后后端:

maven

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

然后是

配置

package com.oddfar.campus.business.config;

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

@Configuration
public class WebSocketClientConfig {

    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

主代码

package com.oddfar.campus.business.service;

import org.springframework.stereotype.Component;

import javax.websocket.server.ServerEndpoint;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/imserver/{username}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessionMap.put(username, session);
        log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size());
        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();
        result.set("users", array);
        for (Object key : sessionMap.keySet()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("username", key);
            array.add(jsonObject);
        }
        sendAllMessage(JSONUtil.toJsonStr(result));
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        sessionMap.remove(username);
        log.info("有一连接关闭,移除username={}的用户session, 当前在线人数为:{}", username, sessionMap.size());
    }
    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        log.info("服务端收到用户username={}的消息:{}", username, message);
        JSONObject obj = JSONUtil.parseObj(message);
        String toUsername = obj.getStr("to");
        String text = obj.getStr("text");
        Session toSession = sessionMap.get(toUsername);
        if (toSession != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("from", username);
            jsonObject.set("text", text);
            this.sendMessage(jsonObject.toString(), toSession);
            log.info("发送给用户username={},消息:{}", toUsername, jsonObject.toString());
        } else {
            log.info("发送失败,未找到用户username={}的session", toUsername);
        }
    }
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
    /**
     * 服务端发送消息给所有客户端
     */
    private void sendAllMessage(String message) {
        try {
            for (Session session : sessionMap.values()) {
                log.info("服务端给客户端[{}]发送消息{}", session.getId(), message);
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
}

还有,如果你的websocket的ws请求被security拦截了,要配置下,避开websocket请求

package com.oddfar.campus.framework.config;

import com.oddfar.campus.framework.security.filter.JwtAuthenticationTokenFilter;
import com.oddfar.campus.framework.security.handle.AuthenticationEntryPointImpl;
import com.oddfar.campus.framework.security.handle.LogoutSuccessHandlerImpl;
import com.oddfar.campus.framework.security.properties.PermitAllUrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * spring security配置
 *
 * @author ruoyi
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity//这个注解不能缺
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;


    /**
     * 退出处理类
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;


    /**
     * 跨域过滤器
     */
    @Autowired
    private CorsFilter corsFilter;

    /**
     * 允许匿名访问的地址
     */
    @Autowired
    private PermitAllUrlProperties permitAllUrl;

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 注解标记允许匿名访问的url
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());

        httpSecurity
                // CSRF禁用,因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/register", "/captchaImage").anonymous()
                // 静态资源,可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        // 添加Logout filter
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    //忽略websocket拦截
    @Override
    public void configure(WebSecurity webSecurity){
        webSecurity.ignoring().antMatchers(
                "/**"
        );
    }
}

相关推荐

  1. python实现模拟用户行为测试

    2024-04-07 05:38:01       36 阅读
  2. uniapp获取用户头像

    2024-04-07 05:38:01       62 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-07 05:38:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-07 05:38:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-07 05:38:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-07 05:38:01       20 阅读

热门阅读

  1. leetcode 169.多数元素

    2024-04-07 05:38:01       49 阅读
  2. ROC与决策树介绍

    2024-04-07 05:38:01       22 阅读
  3. 在 HTML 中禁用 Chrome 浏览器的 Google 翻译功能

    2024-04-07 05:38:01       37 阅读
  4. MongoDB的简单使用

    2024-04-07 05:38:01       22 阅读
  5. leetcode 72.编辑距离

    2024-04-07 05:38:01       24 阅读
  6. 深入了解go的通道类型

    2024-04-07 05:38:01       17 阅读
  7. 外刊杂志经济学人获取方式

    2024-04-07 05:38:01       18 阅读
  8. golang mutex

    2024-04-07 05:38:01       19 阅读
  9. 【Rust】基础语法

    2024-04-07 05:38:01       21 阅读
  10. 设计模式:外观模式

    2024-04-07 05:38:01       17 阅读
  11. 机器学习软件perming的使用文档

    2024-04-07 05:38:01       15 阅读
  12. AJAX

    AJAX

    2024-04-07 05:38:01      14 阅读
  13. 设计模式:策略模式

    2024-04-07 05:38:01       37 阅读
  14. Spring和Spring Boot的区别

    2024-04-07 05:38:01       20 阅读