首页 > 解决方案 > 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 !== themeif,并将消息发送回初始主题。

正在发送此消息并且event名称与预期一致,但组件上没有任何消息。

标签: node.jssocket.io

解决方案


推荐阅读