Netty 即时通讯 前端 (六)

本编接着上篇后端基于Netty服务器的websocket服务 ,作一个前端的简单展现前端

顺便学习一下前端的知识点,关于js的websocket通讯方式和http请求也差很少,看下面:vue

var socket = new WebSocket("ws://[ip地址]:[端口]");web

ws:// 部分是一个协议,好比http://,https:// 都很相似 ; ip,端口什么的就不说了vue-cli

 

包含如下函数: onopen() , onmessage() , onerror() , onclose() , Socket.send() , Socket.close()element-ui

  • onopen 创建链接时触发
  • onmessage 服务端向客户端发送消息,接收到消息时触发
  • onerror 错误时触发
  • onclose 关闭链接时触发
  • send 主动发送消息给后端,好比回车发消息
  • close 主动关闭socket链接,好比关闭聊天窗口,退出游戏等

看上去像websocket请求的生命周期,前端和后端的通道Channel差很少的生命周期后端

 

函数也很少,理解了做用就能够直接上手操做了,使用vue-cli搭建vue进行测试,很快,并搭配了element-ui构建ui界面服务器

vue页面代码以下: websocket

<template>
  <div id="page">
    <div>
      发送消息:
      <el-input size="medium" style="width:300px" v-model="input_msg" placeholder="发送消息"></el-input>
      <el-button size="medium" @click="send(input_msg)">发送</el-button>
    </div>

    <div>
      接收消息:
      <el-input size="medium" type="textarea" style="width:376px" :rows="2" v-model="get_msg" placeholder="接收消息"></el-input>
    </div>

    <div>
      <el-button size="medium" @click="out()">退出</el-button>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        input_msg: "",
        get_msg: "",
        my_socket: null
      };
    },
    created() { //页面加载时,初始化websocket
      this.initWebsocket()
    },
    destroyed() { //离开时,销毁websocket
      this.out()
    },
    methods: {
      initWebsocket() {
        const ws = "ws://localhost:8081/ws"
        this.my_socket = new WebSocket(ws);
        this.my_socket.onopen = this.ws_onopen;
        this.my_socket.onerror = this.ws_onerror;
        
        this.my_socket.onmessage = this.ws_onmessage;
        this.my_socket.onclose = this.ws_onclose;
      },
      ws_onopen() {
        console.log("链接服务器 成功...")
      },
      ws_onerror() {
        console.log("链接服务器 错误...")
      },
      ws_onmessage(e) {
        console.log("接收消息: " + e.data)
        if(this.get_msg) {
          this.get_msg = this.get_msg + "\n" + e.data
        } else {
          this.get_msg = e.data
        }
      },
      ws_onclose() {
        console.log("链接服务器 关闭...")
      },
      send(sendmsg) {
        console.log("发送信息 >>>>" + sendmsg);
        this.my_socket.send(sendmsg);
      },
      out() {
        console.log("主动退出");
        this.my_socket.close();
      }
    }
  };
</script>

<style>
</style>

 

结合上一篇 后端 ,都启动,简单的页面  测试展现 , 开两个客户端: socket

第一个客户端:函数

第二个客户端: 

发送消息,接收消息都OK的

注意: ws://localhost:8081/ws  最后这个ws是后端定义的路由,不必定是我这边的ws

相关文章
相关标签/搜索