0
目前我想是這樣的:如何在使用套接字時在nodejs中導入代碼?
io.sockets.on('connection', function (client) {
console.log("client connected: " + client.id);
io.sockets.socket(client.id).emit("connected", client.id);
client.on("sendMessage", function (data) {
//send message code
});
});
我想的sendMessage代碼應該是在單獨的文件是什麼。那麼該怎麼辦?
我曾嘗試:
//in first.js:
var events = require('events');
var em = new events.EventEmitter();
var msg = require('./message.js');
var emitter = msg.em;
io.sockets.on('connection', function (client) {
console.log("client connected: " + client.id);
io.sockets.socket(client.id).emit("connected", client.id);
emitter.emit('sendMessage');
});
//in message.js
client.on("sendMessage", function (data) {
//return "Hello";
//perform db operation
});
無論是正確的還是錯誤的?誰能幫忙? 或者是否有任何新的正確方法?
但客戶端我也需要通過。如何在sendMessage中傳遞客戶端? – uday214125
謝謝你回答@rsp,我已經通過socket.on(「sendMessage」,函數(data){sendMessage(client,data); })解決了這個問題。 – uday214125