I have got a node server running locally and setting up a Socket.IO instance.
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();
Then on my website I have got a Vue component, but sometimes I could have 2 of the components, so I wanted to emit messages to BOTH of these component's from my server, I will handle accepting the messages in either Vue Instance myself.
This was working, all of a sudden it's not now, not too sure what I changed.
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;
}
So initially I would run initiate
on one of the components, this sends some the theme name to the server and the server stores the theme in a property. Then I would run initiate
on the second component, which would send a different theme, so this should hit the this.theme && this.theme !== theme
if, and send a message back to the initial theme.
This message is being sent and the event
names are as expected, but nothing comes through on the component.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…