Vue+ssh 프레임 워 크 온라인 채 팅 실현

8549 단어 vue온라인 채 팅
본 논문 의 사례 는 Vue+ssh 프레임 워 크 가 온라인 채 팅 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
효과 도


핵심 부분
웹 소켓 프로 그래 밍
백 스테이지 로 메시지 보 내기

<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());
  }
 }
}
메모:가방 두 개 가 져 오기

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기