2

I want to mix two streams of ordinary socket and WebSocket. All received socket messages should be broadcasted over websocket to all connected users.

I have this part of code:

var net = require('net');
var io = require('socket.io').listen(13673, 'localhost');

net.createServer(function (stream) {
  stream.setEncoding('utf8');
  stream.on('data', function (data) {
    // HERE SHOULD BE WS BROADCAST
    console.log(data);
  });
}).listen(24768);

io.sockets.on('connection', function (socket) {
  socket.on('message', function (text) {
    var message = {
      'type': 'message',
      'received': new Date(),
      'text': text
    };

    socket.broadcast.json.send([message]);
    socket.json.send([message]);
  });
});

So, as apart it works just fine, but I want listen to normal socket all the time and process received messages to WebSocket. Put one into other doesn't work.

2 Answers 2

1

Try keeping an array of connected WebSocket clients, and when you receive a TCP socket message, loop through the array and broadcast to each client:

var net = require('net');
var io = require('socket.io').listen(13673, 'localhost');

var clients = [];

net.createServer(function (stream) {
    stream.setEncoding('utf8');
    stream.on('data', function (data) {
        // HERE SHOULD BE WS BROADCAST
        for(var i = 0; i < clients.length; i++)
            clients[i].json.send(/*your message*/);
        console.log(data);
    });
}).listen(24768);

io.sockets.on('connection', function (socket) {
    clients.push(socket);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Is this the only solution to hold all the sockets as array and then loop thru them? What about performance?
Don't worry about performance until it's a problem. Golden rule of programming.
0

You can use io.sockets.emit function for broadcasting to sockets connected through socket.io

var express = require('express')
        , app = express()
        , server = require('http').createServer(app)
        , io = require('socket.io').listen(server);

server.listen(80);

io.sockets.on('connection', function (socket) {
    console.log("NEW SOCKET");
});

function sendToBrowser(message){
    io.sockets.emit('news', {data: message});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.