我试图在后端使用nodejs socket mysql创建一个聊天应用程序。聊天功能有效,但我试图将消息保存到mysql数据库中。
这里的问题是每次用户加入聊天时,我都会收到无限循环的消息保存到数据库中。我尝试添加mysql后,这个问题就开始了。请知道
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var mysql = require('mysql')
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
// Define our db creds
var pool = mysql.createPool({
connectionLimit : 5,
host : '127.0.0.1',
user : 'xxxx',
password : 'xxxxxxxx',
database : 'notes',
debug : false
});
pool.getConnection(function(err){
if (!!err) {
console.log("error")
}
else{
console.log("Connected")
}
})
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new message', function (data) {
add_status(data,function(res){
if(res){
socket.emit('new message', {username: socket.username, message: data});
} else {
socket.emit('error');
}
});
});
var add_status = function (data,callback) {
pool.getConnection(function(err,connection){
if (err) {
callback(false);
return;
}
connection.query("INSERT INTO `note` (`username`, `message`) VALUES ('"+socket.username+"', '"+data+"')"
,function(err,rows){
connection.end();
if(!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
// when the client emits 'add user', this listens and executes
socket.on('add user', function (userDetail) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = userDetail.user.name;
socket.token = userDetail.token;
console.log("token", userDetail.token);
console.log("username", userDetail.user.name);
++numUsers;
addedUser = true;
socket.emit('login', {username: socket.username, numUsers: numUsers});
socket.emit('user joined', {username: socket.username, numUsers: numUsers});
});
});