为什么socket.io无法连接?

时间:2020-05-19 23:20:34

标签: node.js express sockets

服务器代码

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config()
}

const express = require('express')
const app = express()
const expressLayouts = require('express-ejs-layouts')
const {MongoClient} = require('mongodb')
const indexRouter = require('./routes/index')
const registerRouter = require('./routes/register')
const loginRouter = require('./routes/login')
const gameRouter = require('./routes/game')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const server = require('http').Server(app)
var io = require('socket.io')(server, {})
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true })
const db = mongoose.connection

app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.set('layout', 'layouts/layout');
app.use(expressLayouts);
app.use(express.static('public'));
app.use(express.urlencoded({ extended : false }))
app.use(bodyParser.urlencoded({limit: '10mb', extended: false}))
app.use('/', indexRouter);
app.use('/register', registerRouter);
app.use('/login', loginRouter);
app.use('/game', gameRouter);
server.listen(process.env.PORT || 3000);
console.log("Server started.");

db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to mongoose'))

客户代码

const express = require('express')
const app = express()
const router = express.Router()
const { handleError, ErrorHandler } = require('../models/error')
const server = require('http').Server(app)
const io = require('socket.io')(server)



var SOCKET_LIST = {}

router.get('/', (req, res) => {
    console.log('reached here')
    res.render('game')
})
io.sockets.on('connection', function(socket){
    console.log('socket connection');

    socket.on('happy',function(data){
        console.log('happy because ' + data.reason);
    });

    socket.emit('serverMsg',{
        msg:'hello',
    });

});

setInterval(() => {
    for(var i in SOCKET_LIST) {
        var socket = SOCKET_LIST[i];
        socket.x++
        socket.y++
        socket.emit('newPosition', {
            x: socket.x,
            y: socket.y
        });
    }
}, 1000/25);

module.exports = router

index.ejs

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect();

    var random = Math.random();

    var happy = function(){
        socket.emit('happy',{
            reason:'its my birthday' + random
        });
    }

    socket.on('serverMsg',function(data){
        console.log(data.msg); 
    });


</script>

<button onclick="happy()">Happy</button>

大家好,我是node / express的新手,还问过堆栈溢出问题。我想把sockets.io作为我参与的项目的一部分来解决。现在这是问题所在,每当我渲染index.ejs文件时,我都希望在终端上打印一个“套接字连接”。但是,这种情况不会发生,这使我相信未建立与套接字的连接。任何想法为什么会这样吗?

0 个答案:

没有答案