node.js - Receive socket.io messages outside of connection
问题描述
I know that messages can be sent outside the socket connection code block. How can I receive messages from the client the same way?
// Create socket.io server attached to current HTTP server
var io = require('socket.io')(server);
// When connection is made, set up some definitions for the server's connections
io.on('connection', (socket) => {
console.log('Local server connected...');
socket.on('disconnect', () => {
console.log('Local server disconnected...');
});
// I can receive messages here
socket.on('sendToRemote', function (data) {
console.log(data);
});
});
// Messages can be received outside the socket code using this syntax:
io.of('/').emit('runCamera', "Client connected...");
// I can't receive messages here...
// How can the server receive messages outside the socket code?
// I tried using the code below but it didn't work.
// Syntax compiles but doesn't work like the one above.
io.of('/').on('sendToRemote', function (data) {
console.log(data);
});
解决方案
您需要有一个套接字来从中获取消息。你可以发射到一个房间,因为它正在跟踪连接到那个房间的所有插座。因此,要仅在特定房间中获取消息:
io.of('/').on('connection', function (socket) {
socket.on("sendToRemote", function (data) {
console.log(data);
});
});
推荐阅读
- html - 角弹性布局挑战
- odoo - 如何避免odoo 10 nvd3饼图中的文本重叠
- ios - 如何下载和安装 iXGuard for iOS 应用程序?
- python - 在使用 pytest 测试烧瓶应用程序中使用模拟服务器
- python - 使用 kubernetes 客户端 corev1api 运行 `connect_get_namespaced_pod_exec` 会产生错误的请求
- c - 用一个空格替换一个或多个空格的字符串的程序。不能使用任何库函数。这不是 EOF 版本
- laravel - Laravel 表单验证消息视图
- c# - 在@Ajax.ActionLink html 样式不工作 MVC,AJAX.ActionLink
- java - java应用程序响应太长,这个火焰图意味着什么?
- c - 如何将十六进制字符串发送到串口?