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

CSS implements 0.5px lines to solve mobile compatibility issues (recommended)

【content】: 1. Use background-image gradient style...

11 Linux KDE applications you didn't know about

KDE Abbreviation for Kool Desktop Environment. A ...

Detailed explanation of Axios asynchronous communication in Vue

1. First, we create a .json file for interactive ...

Summary of common commands for Linux user and group management

This article summarizes the common commands for L...

TypeScript Enumeration Type

Table of contents 1. Overview 2. Digital Enumerat...

12 Useful Array Tricks in JavaScript

Table of contents Array deduplication 1. from() s...

XHTML Tutorial: XHTML Basics for Beginners

<br />This site’s original content, please i...

Detailed example of creating and deleting tables in MySQL

The table creation command requires: The name of...

Delegating Privileges in Linux Using Sudo

Introduction to sudo authority delegation su swit...

CSS Sticky Footer Implementation Code

This article introduces the CSS Sticky Footer imp...

Native JS to implement hover drop-down menu

JS implements a hover drop-down menu. This is a s...

Detailed tutorial for installing MySQL on Linux

MySQL downloads for all platforms are available a...

Detailed steps for completely uninstalling MySQL 5.7

This article mainly summarizes various problems o...

HTML table tag tutorial (35): cross-column attribute COLSPAN

In a complex table structure, some cells span mul...