[英]How to communicate from server to client via sockets with nodejs?
Currently I am creating a Javascript application. 目前我正在创建一个Javascript应用程序。 I am using AppJS for this.
我正在使用AppJS 。
I have some problems understanding the connection between the client and server. 我在理解客户端和服务器之间的连接时遇到了一些问题。
The problem is the menubar and sockets combination. 问题是菜单栏和套接字的组合。
io.sockets.on('connection', onSocketConnection)
function onSocketConnection(socket) {
socket.emit('onMessage', {
date: new Date(),
message: 'Welcome!'
})
}
var menubar = app.createMenu([{
label:'File',
submenu:[{
label:'New',
action: function() {
// Simply window.reload() or windows.frame.reload()?
// Reload window
}
},{
label:'Change something in view...',
action: function() {
// How to speak to client from here?
// I cannot use socket.emit()
}
}, {
label:'Exit',
action: function() {
window.close()
}
}]
}])
But how to tell the client when the user clicked on the menubar items? 但是如何在用户点击菜单栏项目时告诉客户端?
Another problem using sockets is asynchronous long loading functions. 使用套接字的另一个问题是异步长加载函数。
io.sockets.on('connection', onSocketConnection)
function onSocketConnection(socket) {
var test = veryLongLoading()
console.log(test) // undefined -.-'
socket.emit('test', {
test: test
})
}
So I thought I need to use callbacks like this: 所以我认为我需要使用这样的回调:
io.sockets.on('connection', onSocketConnection)
function onSocketConnection(socket) {
veryLongLoading(returnValue)
}
function veryLongLoadingFunction(next) {
// Blablabla
next('test')
}
function returnValue(value) {
// Again socket is not available -.-'
socket.emit('test', {
test: test
})
}
Anyone faced the same problems or anyone who can point me into the right direction. 任何人都面临同样的问题或任何可以指引我正确方向的人。
Maybe I just misunderstand the flow (I normaly program in PHP) 也许我只是误解了流程(我在PHP中正常编程)
Problem 1 问题1
For the first part, you need to listen to events from the server: 对于第一部分,您需要侦听来自服务器的事件:
socket.on('message-from-server', function(data) {
// You need to trigger the sub-menu change here.
// Which means you need a handle for the sub-menu object.
subMenu.action(data)
});
Problem 2 问题2
The pattern for long running async functions look like this: 长时间运行异步函数的模式如下所示:
var veryLongLoading = function(next) {
// pass your value to next
// like this
next(someValue);
};
Then to use it, you would do this: 然后使用它,你会这样做:
veryLongLoading(function(someValue) {
socket.emit(someValue);
});
Hope that helps! 希望有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.