日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

websocket demo

發布時間:2023/12/10 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 websocket demo 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

git

node.js創建websocket 的服務

Nodejs Websocket包

ws.createServer([options], [callback])
The callback is a function which is automatically added to the “connection” event.

前端代碼

1. 創建實例、打開連接 this.websocket = new WebSocket('ws://127.0.0.1:8001'); # 實例回調 1.1 連接成功 this.websocket.onopen = () => {this.setMessageInnerHTML('WebSocket連接成功'); }; 1.2 接收服務端消息 this.websocket.onmessage = (event) => {this.setMessageInnerHTML(event.data); }; 2. 關閉連接 this.websocket.close(); 3. 發送消息 this.websocket.send(message);

完整代碼

  • 后端
var ws = require('nodejs-websocket'); console.log('開始建立連接...')ws.createServer(function (conn) {conn.on('text', function (str) {// 收到文本時觸發,str 時收到的文本字符串console.log('瀏覽器給服務端收到的信息為:' + str)conn.sendText('服務器返回內容')})conn.on('close', function (code, reason) {console.log('關閉連接', code, reason)});conn.on('error', function (code, reason) {// 發生錯誤時觸發,如果握手無效,也會發出響應console.log('異常關閉', code, reason)}); }).listen(8001) console.log('WebSocket建立完畢');
  • 前端
<template><div><hr /><button @click="openWebSocket">打開WebSocket連接</button><hr />Welcome<br /><input id="text" type="text" /><button @click="send">發送消息</button><hr /><button @click="closeWebSocket">關閉WebSocket連接</button><hr /><h1 id="message"></h1></div> </template><script> export default {data() {return {websocket: null,};},mounted() {this.openWebSocket();},methods: {//將消息顯示在網頁上setMessageInnerHTML(innerHTML) {document.getElementById('message').innerHTML += innerHTML + '<br/>';},//關閉WebSocket連接closeWebSocket() {this.websocket.close();},//發送消息send() {var message = document.getElementById('text').value;this.websocket.send(message);},//打開WebSocket連接openWebSocket() {//判斷當前瀏覽器是否支持WebSocketif ('WebSocket' in window) {this.websocket = new WebSocket('ws://127.0.0.1:8001');} else {alert('當前瀏覽器 Not support websocket');}//連接發生錯誤的回調方法this.websocket.onerror = () => {this.setMessageInnerHTML('WebSocket連接發生錯誤');};//連接成功建立的回調方法this.websocket.onopen = () => {this.setMessageInnerHTML('WebSocket連接成功');};//接收到消息的回調方法this.websocket.onmessage = (event) => {this.setMessageInnerHTML(event.data);};//連接關閉的回調方法this.websocket.onclose = () => {this.setMessageInnerHTML('WebSocket連接關閉');};//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。window.onbeforeunload = () => {this.closeWebSocket();};},}, }; </script><!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 {margin: 40px 0 0; } ul {list-style-type: none;padding: 0; } li {display: inline-block;margin: 0 10px; } a {color: #42b983; } </style>

也可以在前端引入socket.io的cdn,后端用express搭建(也要require socket.io)

前端代碼:

總結

以上是生活随笔為你收集整理的websocket demo的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。