Vue+ssh framework to realize online chat

Vue+ssh framework to realize online chat

This article shares the specific code of Vue+ssh framework to realize online chat for your reference. The specific content is as follows

Rendering

Core part

Websocket Programming

Send a message to the backend

<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="Please enter content" v-model="textarea" class="text"></el-input>
    </el-col>
     <el-col :span="6">
       <br>
      <el-button type="primary" round @click="mess()">Send message</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");//Current user avatar var identity=localStorage.getItem("identity");//Current identity var name=localStorage.getItem("username");//Current username//Get a teacher's name from the previous page var teacher='';
export default {
   components:
      my
  },
  methods: {
    //Call this.websocketsend() in the method to send data to the server onConfirm() {
      //Data to be transmitted var data="Hello";
      this.websocketsend(JSON.stringify(data));
    },
//Click to send the message to the background mess(){
        var mydata=this.textarea;
         let data = {msg: mydata};
      this.websocketsend(JSON.stringify(data));
    },
    /* */
    initWebSocket() {
      // Initialize weosocket
      //Get the current username 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() {
      // After the connection is established, execute the send method to send data let data = { code: 0, msg: "This is client: first connection" };
    },
    websocketonerror() {
      console.log("WebSocket connection failed");
    },
    websocketonmessage(e) {
      // Data receiving var s=eval('(' + e.data + ')');
  //Insert all the data into it this.mycontent.push({mess:s.msg,time:s.date,bl:s.isSelf,mylogo:mylogo});
    },
    websocketsend(Data) {
      // Data sending this.websock.send(Data)
    },
    websocketclose(e) {
      // Close console.log("Connection closed", e);
    }
  },
  created() {
    console.log("created");
    this.initWebSocket();
  },
  data() {
    return {
     websocket: null,
     textarea:'' ,
     mycontent:[],
     iden:true
     };
  },
  destroyed() {
    this.websock.close();
  }
};
</script>

Component 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>

Background code

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 {
 //Date private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
 //Store a collection of sessions, value type is 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("Close");
 }
 @OnError
 public void error(Throwable t) {
  // Add error handling operation close();
  System.out.println("Error occurred");
  
  t.printStackTrace();
 }
 @OnMessage
 public void message(String message,Session session){
  JSONObject jsonObject = JSONObject.fromObject(message);
  jsonObject.put("date", DATE_FORMAT.format(new Date()));
  //Give the current collection size to the front desk, otherwise, I don't know how to store itjsonObject.put("cusize",map.size());
 //Receive information 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());
  }
 }
}

Note: Import two packages

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue+express+Socket realizes chat function
  • Vue implements chat interface
  • Vue realizes web online chat function
  • Vue+web terminal imitates WeChat web version chat room function
  • Vue.js imitates WeChat chat window to display component functions
  • Vue + socket.io implements a simple chat room sample code
  • A single-page application function imitating mobile QQ based on Vue2 (access to chatbot)
  • How to use RongCloud IM to implement chat function in Vue Cli 3 project
  • WeChat robot chat function example implemented by Vue [with source code download]
  • Multi-person online chat room based on vue and websocket

<<:  How to solve the problem of case insensitivity in MySQL queries

>>:  The whole process of installing and configuring Harbor1.7 on CentOS7.5

Recommend

Detailed steps to install VMware Tools from scratch (graphic tutorial)

VMware Tools is a tool that comes with VMware vir...

How to run sudo command without entering password in Linux

The sudo command allows a trusted user to run a p...

How to reset the root password in CentOS7

There are various environmental and configuration...

React implements the sample code of Radio component

This article aims to use the clearest structure t...

Summary of WEBAPP development skills (notes for mobile website development)

1. To develop web responsively, the page must ada...

How to deploy code-server using docker

Pull the image # docker pull codercom/code-server...

CentOS 7.6 installation of MySQL 5.7 GA version tutorial diagram

Table of contents Environment Preparation Environ...

Node and Python two-way communication implementation code

Table of contents Process Communication Bidirecti...

Detailed explanation of component communication in react

Table of contents Parent component communicates w...

4 Ways to Quickly Teach Yourself Linux Commands

If you want to become a Linux master, then master...

JavaScript determines whether the browser is IE

As a front-end developer, I can’t avoid IE’s pitf...

SQL insert into statement writing method explanation

Method 1: INSERT INTO t1(field1,field2) VALUE(v00...

Solution to slow network request in docker container

Several problems were discovered during the use o...

Super detailed steps to install zabbix3.0 on centos7

Preface Recently, part of the company's busin...

How to generate mysql primary key id (self-increment, unique and irregular)

Table of contents 1. Use the uuid function to gen...