我已经实现了一个简单的聊天应用程序。但是当客户端离开页面或关闭浏览器选项卡时,断开连接事件被多次调用。有时两次有时三次。在断开回调函数内部,我将聊天记录插入数据库。由于回调函数多次调用相同的聊天记录,因此多次插入。不知道是什么问题。请帮忙。
代码是这样的
服务器端代码
var sys = require('sys');
var fs = require('fs');
var io = require('socket.io');
var connection = function(){
sys.puts("Here")
var mysql = require('mysql');
var sql = mysql.createConnection({
host:'localhost',
port:3306,
user:'root',
password:'root'
});
sql.query('use chat');
sys.puts("Here" +sql)
return sql;
}
var Server = require('http').createServer(function(req, response){
sys.puts("request recieved");
response.writeHeader(200,{"Content-Type":"text/html"});
response.write("Hello World");
var rs = fs.createReadStream(__dirname + '/chat.html')
sys.pump(rs,response);
});
var history = "";
var socket = io.listen(Server);
var mysql = connection();
socket.sockets.on('connection',function(client){
sys.puts("socket connected ID "+client.id);
sys.puts("session id",client.handshake.sessionID)
var username;
client.send('Welcome to chat');
client.send('Enter your name');
client.on('message',function(message){
if(!username)
{
username = message;
client.send('Welcome,' +username);
return;
}
feedback = username+' sent:'+message;
history = history + feedback + '\n';
client.send(feedback)
client.broadcast.send(feedback);
sys.puts("History is " +history);
sys.puts("mysql" +mysql);
client.on('disconnect',function(){
mysql.query('insert into tblchatHistory (fldChatHistory) values ("'+history+'")',function(err){
sys.puts("error" +err);
history = "";
})
sys.puts("socket connected ID "+client.id);
})
})
})
Server.listen(4000);
客户端代码
<script type="text/javascript">
var socket;
socket = new io.connect("http://localhost:4000");
var connect = false;
socket.on('connect',function(){
alert("connected "+socket.socket.sessionid);
connect = true;
})
function chat()
{
socket.on('message',function(message){
var data = message;
var list ='<li>' +data +'</li>'
document.getElementById("log").innerHTML +=list;
})
}
function sendMsg(event)
{
var entry = document.getElementById("entry");
var msg = entry.value;
if(event.keyCode != 13)return
if(msg)
{
if(connect)
{
socket.emit('message',msg);
entry.value = "";
}
}
}
</script>
<body onload="chat();">
<h1>Chat</h1>
<div><ul id="log"></ul></div>
<div id="console">
<input type="text" id="entry" onkeypress="sendMsg(event);"/>
</div>
<div><a href="http://localhost:8085/BillDesk/welcomeJSF.jsf" >Exit chat</a></div>
</body>