WebSocket Demo

527 阅读1分钟

目录结构

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

安装nodejs-websocket

cnpm i nodejs-websocket --save

app.js

var ws = require('nodejs-websocket');
let conn
var server = ws.createServer(function(c){
  conn = c
  console.log('连接成功');
  c.on("text", function (str) {
    console.log("Received " + str)
    c.sendText(`我收到你发送的"${str}"消息了`)
  })
  c.on("close", function (code, reason) {
      console.log("cection closed")
  })
})
server.listen(2333)

index.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div class="msgs">
      <h3>接收到的消息</h3>
      <div class="item" v-for="(item, index) in msgs"> {{item}}</div>
    </div>
    <div class="send">
      <input type="text" v-model="text">
      <button @click="send">发送消息</button>
    </div>
  </div>
<script>
  new Vue({
    el: '#app',
    data () {
      return {
        text: 'dd',
        msgs: []
      }
    },
    mounted () {
      this.ws = new WebSocket('ws://localhost:2333');
      this.ws.onopen = function () {
        alert('连接成功')
      }
      this.ws.onerror = function () {
        alert('链接失败')
      }
      this.ws.onmessage = this.onmessage
    },
    methods: {
      onmessage (e) {
        this.msgs.push(e.data)
      },
      send () {
        this.ws.send(this.text)
        this.text = ''
      }
    }
  })
</script>
</body>
</html>