简体   繁体   中英

Node.JS WebSocket and Socket

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.

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);
});

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});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM