The framework uses the WS library of the uniapp. node webSocket library

WS module

Ws is a third-party Websocket communication module, which needs to install NPM I WS. The communication model of Websocket is the same as HTTP, and the server side corresponds to the client side model.

uni-app

Uni-app is a framework for developing all front-end applications using vue.js. Developers write a set of code that can be published to iOS, Android, Web (responsive), mini programs (wechat/Alipay/Baidu/Toutiao /QQ/ Kuaishou/Dingding/Taobao), Kuaiapp and many other platforms.

The client

* // Initialize the webSocket and place it in onLoad

    init() {
            if (typeof(WebSocket) === "undefined") {
                    alert("Your browser does not support sockets")}else {
                    // instantiate the socket
                    this.socket = new WebSocket('ws: / / 127.0.0.1:8112')
                    // Listen for socket connections
                    this.socket.onopen = this.open
                    // Listen for socket errors
                    this.socket.onerror = this.error
                    // Listen for socket messages
                    this.socket.onmessage = this.getMessage
                    // The listening server is down
                    this.socket.onclose = this.close
            }
    },
    // Send a message to the server
    send(params) {
            console.log('ffsdas', params)
            this.socket.send(params)
            let userMsg = {
                    user: true.content: params,
            }
            this.chatList.push(userMsg)
            this.inputMsg = ' '
    },

![1630659113(1).png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/300c5fac65a74d9b910596ada42deb09~tplv-k3u1fbpfcp-watermark.image)! [1630659135(1).png](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4afa998a0bd1413b8b95ae96c553a776~tplv-k3u1fbpfcp-watermark.image)## Server codeCopy the code

The WS module needs to be installed

npm install ws

` ```js const port = process.env.PORT || 8112 const WebSocket = require('ws'); // Import module const wsObj = new websocket.server ({port},()=>{// Monitor interface console.log("socket start")}) // The Server is connected by the client Wsobj.on ('connection', (ws) => {// Through the ws object, Log (ws, 'ws') ws. On ('message', (message) => {// Through the ws object, Log (message.tostring (), 'message') ws.send(' Hello, I'm a robot from webSocket ')})}) 'Copy the code