问题是,每当我尝试触发"this.io.emit"事件时,就会发生TypeError.它仅在我在"socket.on"块内写入此语句"this.io.emit"时给出,否则,如果我在该块之外写入它则不会产生错误.
这是调用其他库的主要server.js文件:
const express = require('express'),
http = require('http'),
socketio = require('socket.io');
class App{
constructor()
{
this.port = process.env.PORT || 81;
this.host = `localhost`;
this.app = express();
this.http = http.Server(this.app);
this.socket = socketio(this.http);
}
appConfig(){
new config(this.app);
}
appRoutes(){
new routes(this.app,this.socket).routesDefault();
}
appDefault(){
this.appConfig();
this.appRoutes();
this.http.listen(this.port,this.host,()=> {
console.log(`Listening`);
});
}}
Run Code Online (Sandbox Code Playgroud)
我的服务器端代码是:
'use strict';
class Routes {
constructor(app,socket) {
this.app = app;
this.io = socket;
this.users=[];
}
routesTemplate()
{
this.app.get('/',function(req,res){
res.render('index');
});
}
socketEvents()
{
this.io.on('connection',(socket) => {
socket.on('send message',function(data)
{ …Run Code Online (Sandbox Code Playgroud)