本編接着上篇後端基於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
看上去像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