How to create a page that shows cursor position of all users connected? Node.js, ws, express

Viewed 1136

I want to create a simple page where I would display mouse coordinates of all the users connected.

I got as far as showing mouse coordinates of a single connected client. Sending the mouse coordinates to the server. Sending the data back. I don't know where to go from here. I'm thinking of how to save every response from the server as an object and then display that object. I'm stuck and don't know of a proper way to solve this assignment.

Server side code.

var express = require('express')
var WebSocket = require('ws')
var app = express()

app.listen(3000, function() {
    console.log("Server started on port 3000")
})
app.use(express.static('public'))

var server = new WebSocket.Server({port: 3200})
server.on('connection', function(socket) {
    console.log("Connected, using WebSocket")
    console.log(server.clients.size)

    socket.on('message', function(msg) {
        server.clients.forEach(function each(client) {
            client.send(msg)
        })
    })
})

Client side.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app" v-on:mousemove="clientCoords">
        <p>{{displayX}}</p>
        <p>{{displayY}}</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>
        var app = new Vue({
            el: '#app',
            data() {
                return {
                    clientInformation: {}
                    ,
                    clientList: [

                    ],
                    clientCoord: {},
                    displayX: '',
                    displayY: '',
                    socket: new WebSocket('ws://localhost:3200')
                }
            },
            methods:{
                clientCoords(e){
                    this.clientInformation.coordX = e.clientX
                    this.clientInformation.coordY = e.clientY
                    this.socket.send(JSON.stringify(this.clientInformation))
                }
            },
            mounted() {
                this.clientList.push(this.clientInformation)
                this.socket.addEventListener('message', (msg) => {
                    this.displayX = JSON.parse(msg.data).coordX
                    this.displayY = JSON.parse(msg.data).coordY
                })
            }
        })
    </script>
    <style>
        #app {
            height: 100%;
        }
        body {
            height: 100%;
        }
        html {
            height: 100%;
        }
    </style>
</body>
</html>
0 Answers
Related