我正在使用node.js,ejs,express,mysql和socket.io。 我的服务器看起来像这样(index.js):
onRemove = (event, data) => {
console.log("onRemove event");
}
render() {
return (
<Label color='teal' content='Label content' removeIcon='delete'
onRemove={this.onRemove} />
);
}
客户:
h1 {
margin-top: calc((100%)/2);
transition: color 0.5s linear, transform 0.5s ease-in-out;
}
基本上,当我重新启动服务器并尝试运行时,例如:module.exports = function(io) {
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: '',
database: 'chat'
});
router.get('/chat/:channel_name', (req, res, next) => {
var channel_name = req.params.channel_name;
// get the countries from the database so we make sure the users are connecting to the correct channel to chat, else redirect to /chat
pool.getConnection((err, connection) => {
if(err) return console.log(err);
connection.query('SELECT * FROM channel WHERE channel_name = ?', channel_name, (err, rows) => {
if(err) return console.log(err)
if(!rows.length){
return res.redirect('/chat')
}
res.render('channel', {channel_name: rows[0].channel_name})
var channel = io.of(`/chat/${rows[0].channel_name}`);
channel.on('connection', function(socket){
socket.join(rows[0].channel_name)
channel.to(rows[0].channel_name).emit('say hi', 'Hi from ' + rows[0].channel_name + '!');
});
});
});
});
router.get('/chat', function(req, res, next) {
res.render('chat');
});
return router;
}
,它显示在html页面上:<!DOCTYPE html>
<html>
<head>
<title><%= channel_name %></title>
</head>
<body>
<div id="message"></div>
</body>
</html>
<script src="/js/lib/jquery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var socket = io(`/chat/<%= channel_name %>`);
socket.on('say hi', function(data){
$('#message').append(`<div>${data}</div>`)
})
</script>
但是,在重新启动页面10次后(第11次),浏览器保持加载状态,并且在命令提示符下显示/chat/uk
,为什么会发生这种情况?
另外,这是使用名称空间的正确方法吗?我想创建用户将连接的多个通道(名称空间),然后私下(房间)一对一聊天
答案 0 :(得分:1)
这是当您不编写响应并允许应用挂起时系统的反应。
GET /chat/uk - - ms - -
“--”为空白,表示没有响应代码,时间或大小。翻译后,您会看到响应的未知属性。
您的代码没有响应,也没有生成错误代码,并且从不进入以下行:
if(err) return console.log(err) //happens twice
return res.redirect('/chat')
res.render('channel', {channel_name: rows[0].channel_name})
问题可能在这条线上:
connection.query('SELECT * FROM channel WHERE channel_name = ?', channel_name, (err, rows) => {
您永远不会关闭与数据库的先前连接。尝试添加
connection.release();
在代码中的某些地方,因为与mysql数据库的可用连接可能已用完。要检查,您可以在这里查看方向 How to get number of unused/used connection in nodejs mysql connection pool ? 或使用这些命令
pool.config.connectionLimit // passed in max size of the pool
pool._freeConnections.length // number of free connections awaiting use
pool._allConnections.length // number of connections currently created, including ones in use
pool._acquiringConnections.length // number of connections in the process of being acquired
让我知道这是否可行,或者是否有后续问题。