L
L
Ler Den2016-10-06 16:46:32
JavaScript
Ler Den, 2016-10-06 16:46:32

How to fix error on nodejs with websocket?

I'm making a chat, with the ability to store history on the server. Connected the 'ws' module to NodeJS.
When I load the chat page, NodeJs crashes with an
error.png
error

var WebSocketServer = new require('ws');
        var webSocketServer = new WebSocketServer.Server({
            port: 8080
        });
        // connected users
        var clients = {};
        // all messages
        var history = [];

        webSocketServer.on('connection', function(socket) {
            var id = Math.random();
            clients[id] = socket;
            clients[id].send(history); //ошибка видимо здесь 

            socket.on('message', function(obj) {
                history.push(obj);
                for (var key in clients) {
                    clients[key].send(obj);
                }
            });

            socket.on('close', function() {
                delete clients[id];
            });
        });

What have I done wrong? In a normal way, the history should be stored in the database, but it is not critical for me to store it in a variable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
s2dent, 2016-10-20
@s2dent

Try like this:

clients[id].send(history, { binary: true, mask: true });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question