The directory structure

  • WebSocket
    • app.js
    • index.html
    • node_modules

The installationnodejs-websocket

cnpm i nodejs-websocket --save
Copy the code

app.js

var ws = require('nodejs-websocket'); Let conn var server = ws.createserver (function(c){conn = c console.log(' connection succeeded '); C. n("text", function (STR) {console.log("Received "+ STR) c. sendtext (' I Received "${STR}" message ')}) c. n("close", function (code, reason) { console.log("cection closed") }) }) server.listen(2333)Copy the code

index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <meta http-equiv=" x-UA-compatible "content=" IE =edge" SRC = "https://cdn.jsdelivr.net/npm/[email protected]" > < / script > < title > Document < / title > < / head > < body > < div id = "app" > < div </h3> <div class="item" v-for="(item, index) in msgs"> {{item}}</div> </div> <div class="send"> <input type="text" v-model="text"> <button </button> </div> </div> <script> new Vue({el: '#app', data () {return {text: 'dd', MSGS: [] } }, mounted () { this.ws = new WebSocket('ws://localhost:2333'); This.ws. Onmessage = function () {alert(' connection failed ')} this.ws. Onmessage = function () {alert(' connection failed ')} this.ws this.onmessage }, methods: { onmessage (e) { this.msgs.push(e.data) }, send () { this.ws.send(this.text) this.text = '' } } }) </script> </body> </html>Copy the code