node.js - Socket.IO 服务器发送到两个客户端
问题描述
我有一个节点服务器在本地运行并设置了一个 Socket.IO 实例。
const http = require('http');
const socket = require('socket.io');
const path = require('path');
class Controller
{
constructor() {
this.localURL = path.resolve(process.cwd() + '/themes/');
this.theme = null;
const server = http.createServer();
this.io = new socket.Server(server, {
transports: ['websocket'],
});
this.io.on("connection", socket => {
// Wait for the client to send the website theme
socket.on('init', theme => {
// Inform current running client that the server is changing projects.
if (this.theme && this.theme !== theme) {
socket.emit(`message-${this.theme}`, {
type: 'message',
message: `Project changed to ${theme}, stopping ${this.theme}.`
});
return;
}
// Set the theme
this.theme = theme;
});
});
server.listen(8080);
}
}
new Controller();
然后在我的网站上我有一个 Vue 组件,但有时我可以有 2 个组件,所以我想从我的服务器向这两个组件发出消息,我将自己处理在任一 Vue 实例中接受消息。
这是有效的,突然之间不是现在,不太确定我改变了什么。
import { io } from 'socket.io-client';
export default {
props: [ 'code' ],
mounted: function () {
this.socket = io('ws://localhost:8080', {
forceNew: true,
timeout: 10000,
transports: ['websocket']
});
this.socket.on('connect', () => {
this.connected = true;
});
this.socket.on('disconnect', () => {
this.connected = false;
this.initiated = false;
});
this.socket.on(`stop-${this.code}`, () => {
this.started = '';
});
this.socket.on(`message-${this.code}`, message => {
console.log(message);
message.time = 'N/A';
this.messages.unshift(message);
})
this.socket.onAny((event, data) => {
if (event.indexOf(this.code) > -1) {
return;
}
event = event.replace(`-${this.code}`, '');
this[event] = data;
});
},
methods: {
initiate() {
this.messages = [];
this.socket.emit('init', this.code);
this.socket.on('started', code => {
if (code !== this.code) {
console.log('Themes don\'t match...');
this.initiated = false;
return;
}
所以最初我会initiate
在其中一个组件上运行,这会将一些主题名称发送到服务器,然后服务器将主题存储在一个属性中。然后我会initiate
在第二个组件上运行,它会发送一个不同的主题,所以这应该点击this.theme && this.theme !== theme
if,并将消息发送回初始主题。
正在发送此消息并且event
名称与预期一致,但组件上没有任何消息。
解决方案
推荐阅读
- vba - 如何在访问中使用 VBA 将变量从一个 From 传递到另一个表单
- ruby-on-rails - 嵌套控制器中的 Rails 6 Dup
- python - 包含不同 dtype 的 numpy 数组的 Numpy 数组
- amazon-web-services - Snakemake 和 Tibanna:找不到字段“snakemake_main_filename”
- bash - Bash:结合创建文件并将路径存储在变量中
- java - 如何分析 OutOfMemory GWT 错误并自定义堆?
- python - 要列出的 LinearSegmentedColormap
- javascript - 如何从输入中获取占位符?
- java - readObject() 不读取数组
- python - 从 python 类创建一个 vim 实例?