简体   繁体   中英

Send data from websocket to socket.io


I used websocket interface to connect to websocket server . what if i want send data that i receive from the websocket server through my websocket interface to client connected to me through http server , should i use socket.io ?

在此输入图像描述

so at the end i will have socket.io attached to to http server and websocket interface to get data and in case of message come will be send to client through socket.io . is that the best setup ?

Code Example :

// Require HTTP module (to start server) and Socket.IO
var http = require('http'),
    io = require('socket.io');
var WebSocket = require('ws');


var ws = new WebSocket('ws://localhost:5000');

// Start the server at port 8080
var server = http.createServer(function (req, res) {

    // Send HTML headers and message
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

ws.on('open', function open() {
    ws.send('something');
});

ws.on('message', function (data, flags) {
    // here the data will be send to socket.io
});

// Add a connect listener
socket.on('connection', function (client) {

    // Success!  Now listen to messages to be received
    client.on('message', function (event) {
        console.log('Received message from client!', event);
    });
    client.on('disconnect', function () {
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});

Yes, your design is correct.

However, one thing that you should keep in mind is take care of sending the message to the correct client after authentication. In my opinion, it is very easy to make this mistake, partially because of the simplicity of messaging using websockets.

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