gpt4 book ai didi

javascript - Socket.io mysql 连接错误

转载 作者:行者123 更新时间:2023-11-29 11:19:05 27 4
gpt4 key购买 nike

当我在 npm 上启动套接字时,我的 Mysql 连接将关闭大约 30 秒。我不知道为什么。 mysql插入方法有效。但是当我等待大约 1 分 -30 秒时,连接关闭了。

这是错误代码;

events.js:141 throw er; // Unhandled 'error' event ^

Error: Connection lost: The server closed the connection. at Protocol.end (C:\xampp\htdocs\tem\node_modules\mysql\lib\protocol\Protocol.js:109:13) at Socket. (C:\xampp\htdocs\tem\node_modules\mysql\lib\Connection.js:115:28) at emitNone (events.js:72:20) at Socket.emit (events.js:166:7) at endReadableNT (_stream_readable.js:921:12) at nextTickCallbackWith2Args (node.js:442:9) at process._tickCallback (node.js:356:17)

这是我的源代码;

var app = require('express')();
var mysql = require("mysql");
var http=require('http').Server(app);
var io=require('socket.io')(http);
var con = mysql.createConnection({
host: "hostname",
user: "username",
password: "pw",
database: "db"
});
con.connect(function(err){
if(err){
console.log('UnSuccesfull');
return;
}
console.log('Succesfull');
});
app.get("/",function(req,res){

res.sendfile(__dirname+"/asd.html");

});
io.on('connection',function(socket){

var UserLog={
Log:'A User Connected'
};
con.query('Insert Into Log SET ?',UserLog ,function(err){
if(err)
console.log(err);
});
});
var port=xx;
http.listen(port,'xx.xx.xx');

最佳答案

我向您推荐使用连接池。

你可以像这样创建连接池;

var pool  = mysql.createPool({
connectionLimit : 60,
host : hostname,
user : dbUser,
password: dbPass,
database: dbName,
multipleStatements: true
});

当你需要在mysql上运行查询时;

pool.getConnection(function(err, connection) {
connection.query( "SELECT * FROM `users`", function(err, users) {
connection.release();
});
});

关于javascript - Socket.io mysql 连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39253896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com