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 explanation of psql database backup and recovery in docker

1. Postgres database backup in Docker Order: dock...

XHTML introductory tutorial: Application of table tags

<br />Table is an awkward tag in XHTML, so y...

Linux system file sharing samba configuration tutorial

Table of contents Uninstall and install samba Cre...

Install multiple versions of PHP for Nginx on Linux

When we install and configure the server LNPM env...

Summary of Button's four Click response methods

Button is used quite a lot. Here I have sorted ou...

MySQL slow query pt-query-digest analysis of slow query log

1. Introduction pt-query-digest is a tool for ana...

JavaScript to achieve all or reverse selection function

This article shares the specific code of JavaScri...

How to create a flame effect using CSS

The main text starts below. 123WORDPRESS.COM Down...

How to import Excel files into MySQL database

This article shares with you how to import Excel ...

Detailed explanation of MySQL combined index method

For any DBMS, indexes are the most important fact...

Detailed explanation of where the image pulled by docker is stored

20200804Addendum: The article may be incorrect. Y...