从外部获取套接字值(socket.io)

时间:2018-05-20 15:41:38

标签: socket.io

let app = require('express')();
let server = require('http').Server(app);
let io = require('socket.io')(server);

io.on('connection', function (socket) {
 // I want to get this value from outside
})

我想知道如何使用我们的值socket ..我必须在另一个函数中使用socket.emit()

const WebSocket = require('html5-websocket');
const agent_websock = new WebSocket('ws://ip:post/');
   agent_websock.onmessage = function (m) {
        let msg = JSON.parse(m.data);
        console.log(msg, 'agent');
        socket.emit('news', {msg: msg});
    };

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式从外部获取套接字值

<强> ==&GT; app.js

var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen(3000, function () {
    console.log('Listening on port 3000 ...');
});
socket.socketStartUp(server);
module.exports = app;

<强> ==&GT; helper.js

var helperFunction = {}
helperFunction.emitMessage = function (socket) {
    socket.emit('event_name',{'key':'value'})
}
module.exports = helperFunction;

<强> ==&GT; socketServer.js

var io = require('socket.io')();
var helper = require('helper');
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
    io.attach(server
    io.on('connection', function (socket) {
        console.log("New user is connected with socket:", socket.id);
        helper.emitMessage(socket);
    })
}
module.exports = socketFunction;

希望这个答案能够解决你的问题