Vue+ssh框架实现在线聊天

 更新时间:2021年06月28日 13:59:32   投稿:lijiao  
这篇文章主要为大家详细介绍了Vue+ssh框架实现在线聊天,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Vue+ssh框架实现在线聊天的具体代码,供大家参考,具体内容如下

效果图

核心部分

websocket编程

向后台发送消息

<template>
<el-container>
  <el-header >
  </el-header>
  <el-main>
    <div class="cht">
   <div v-for="(d,index) in mycontent" :key="index">
      <my :message="d.mess" :time="d.time" :bl="d.bl"></my>
      </div>
      </div>
<div class="smess">
  <el-row>
    <el-col :span="18">
<el-input type="textarea"  placeholder="请输入内容"   v-model="textarea" class="text"></el-input>
    </el-col>
     <el-col :span="6">
       <br>
      <el-button type="primary" round  @click="mess()">发送消息</el-button>
    </el-col>
  </el-row>
  </div>
  </el-main>
</el-container>
</template>
<style>
.smess{
  left: 20%;
  width:70%;
  position: absolute;
  top:70%
}
.text{
border: 1px solid #409eff;
}
.cht{
width: 55%;
height: 30%;
background-color: burlywood;
margin-left: 18%;
}
</style>
<script>
import router from "../../router/router.js";
import my from "./my";
import axios from "axios";
import Qs from "qs";
var mylogo=localStorage.getItem("logo");//当前的的用户头像
var identity=localStorage.getItem("identity");//当前身份
  var name=localStorage.getItem("username");//当前用户名
  //从上一个页面获取一个老师名称
  var teacher='';
export default {
   components: {
      my
  },
  methods: {
    //在方法里调用this.websocketsend()发送数据给服务器
    onConfirm() {
      //需要传输的数据
      var data="你好";
      this.websocketsend(JSON.stringify(data));
    },
//点击发送把消息给后台
    mess(){
        var mydata=this.textarea;
         let data = {msg: mydata};
      this.websocketsend(JSON.stringify(data));
    },
    /* */
    initWebSocket() {
      // 初始化weosocket
      //获取当前的用户名
      this.websock = new WebSocket(
        "ws://localhost:8080/PsychoSys/javasocket/" +name
      );
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = this.websocketonerror;
      this.websock.onopen = this.websocketonopen;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      // 连接建立之后执行send方法发送数据
      let data = { code: 0, msg: "这是client:初次连接" };
    },
    websocketonerror() {
      console.log("WebSocket连接失败");
    },
    websocketonmessage(e) {
      // 数据接收
   var s=eval('(' + e.data + ')');
  //把数据都插入到里面去
  this.mycontent.push({mess:s.msg,time:s.date,bl:s.isSelf,mylogo:mylogo});
    },
    websocketsend(Data) {
      // 数据发送
    this.websock.send(Data)
    },
    websocketclose(e) {
      // 关闭
      console.log("已关闭连接", e);
    }
  },
  created() {
    console.log("created");
    this.initWebSocket();
  },
  data() {
    return {
     websocket: null,
     textarea:'' ,
     mycontent:[],
     iden:true
     };
  },
  destroyed() {
    this.websock.close();
  }
};
</script>

组件my.vue

<template>
<div v-if="bl" class="rborders">
  <el-row class="ms">
    <el-col :span="22">
      <el-row><span>{{message}}</span></el-row>
      <br>
       <el-row><span class="time">{{time}}</span></el-row>
  </el-col>
    <el-col :span="2" >
      <img src="mylogo" class="logo"/>
  </el-col>
    </el-row>
  </div>
  <div v-else class="lborders">
 <el-row>
  <el-col :span="2" >
      <img src="http://localhost:8080/PsychoSys/title/user.png" class="logo"/>
  </el-col>
  <br>
    <el-col :span="12">
      <el-row >
        <el-col :span="24"><span >{{message}}</span></el-col>
        </el-row>
      <br>
       <el-row><span class="time">{{time}}</span></el-row>
  </el-col>
    </el-row>
  </div>
</template>
<style>
.ms{
text-align: right;
margin-right: 0%;
}
.logo{
    width:60px;
    height: 60px;
    border-radius: 50%;
}
.time{
  font-size:14px;
}
.lborders{
  position: relative;
  margin-left:0%;
}
.rborders{
  position: relative;
  margin-right:0%;
}
</style>
<script>
export default {
   props: ['message','time','bl','mylogo'],
     data() {
        return {
     };
      },
}
</script>

后台代码

package cn.com.socket;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
 
import org.hibernate.SessionFactory;
 
import net.sf.json.JSONObject;
@ServerEndpoint("/javasocket/{uname}")
public class SocketPart {
 //日期化
 private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
 //存储会话的集合,value类型是java类class SocketPart
 private static Map<String,SocketPart> map=new ConcurrentHashMap<String,SocketPart>();
    private String username;
    private Session session;
 private SessionFactory sf;
 public SessionFactory getSf() {
  return sf;
 }
 public void setSf(SessionFactory sf) {
  this.sf = sf;
 }
 @OnOpen
 public void open(@PathParam("uname")String username,Session session){
  this.username=username;
  this.session=session;
  map.put(username,this);
 }
 @OnClose
 public void close(){
  map.remove(this.username);
  try {
   this.session.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("关闭");
 }
 @OnError
 public void error(Throwable t) {
  // 添加处理错误的操作
  close();
  System.out.println("发生错误");
  
  t.printStackTrace();
 }
 @OnMessage
 public void mess(String message,Session session){
  JSONObject jsonObject = JSONObject.fromObject(message);
  jsonObject.put("date", DATE_FORMAT.format(new Date()));
  //把当前集合的大小给前台,不然的话,就不知道怎么存储
  jsonObject.put("cusize",map.size());
 //接收到信息
  for (String s : map.keySet()) {
   if(this.username.equals(map.get(s).username)){
    jsonObject.put("isSelf", true);
   }else{
    jsonObject.put("isSelf", false);
   }
   map.get(s).session.getAsyncRemote().sendText(jsonObject.toString());
  }
 }
}

注意:导入两个包

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • vue 实现把路由单独分离出来

    vue 实现把路由单独分离出来

    这篇文章主要介绍了vue 实现把路由单独分离出来,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Vue3更高效的构建工具Vite使用指南

    Vue3更高效的构建工具Vite使用指南

    这篇文章主要给大家介绍了关于Vue3更高效的构建工具Vite使用的相关资料,Vite是一种面向现代浏览器的一个更轻、更快的前端构建工具,能够显著提升前端的开发体验,需要的朋友可以参考下
    2023-10-10
  • axios在Vue3中的使用实例代码

    axios在Vue3中的使用实例代码

    Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js,这篇文章主要介绍了axios在Vue3中的使用,需要的朋友可以参考下
    2023-07-07
  • vue使用js-audio-recorder实现录音功能

    vue使用js-audio-recorder实现录音功能

    这篇文章主要为大家详细介绍了vue如何使用js-audio-recorder实现录音功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-12-12
  • 利用Vue-cli搭建Vue项目框架的教程详解

    利用Vue-cli搭建Vue项目框架的教程详解

    这篇文章主要为大家详细介绍了利用Vue-cli搭建Vue项目框架的相关资料,对大家深入了解Vue有一定的帮助,感兴趣的小伙伴可以了解一下
    2023-02-02
  • vue2.0 elementUI制作面包屑导航栏

    vue2.0 elementUI制作面包屑导航栏

    本篇文章主要给大家详细代码讲解了vue2.0 elementUI制作面包屑导航栏的过程,对此有兴趣的朋友可以学习下。
    2018-02-02
  • Vue使用Multiavatarjs生成自定义随机头像的案例

    Vue使用Multiavatarjs生成自定义随机头像的案例

    这篇文章给大家介绍了Vue项目中使用Multiavatarjs生成自定义随机头像的案例,文中通过代码示例介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2023-10-10
  • vue篇之事件总线EventBus使用示例详解

    vue篇之事件总线EventBus使用示例详解

    这篇文章主要为大家介绍了vue篇之事件总线EventBus使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 在Vue中使用this.$store或者是$route一直报错的解决

    在Vue中使用this.$store或者是$route一直报错的解决

    今天小编就为大家分享一篇在Vue中使用this.$store或者是$route一直报错的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • electron打包中的巨坑解决记录

    electron打包中的巨坑解决记录

    这篇文章主要为大家介绍了electron打包中的巨坑解决记录,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03

最新评论