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});
};
答案 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;
希望这个答案能够解决你的问题