开发者

Node.JS WebSocket and Socket

开发者 https://www.devze.com 2023-04-11 07:28 出处:网络
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 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) {
开发者_StackOverflow  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});
}
0

精彩评论

暂无评论...
验证码 换一张
取 消