为什么Socket Server停止工作?

时间:2014-05-30 15:44:11

标签: node.js sockets socket.io

我正在为在线游戏创建一个WebSocket。我有一些完美的代码,但一段时间后服务器停止Socket。我不知道什么是错的,我没有错误或什么。它只是停止运行。

有谁知道这段代码有什么问题?

var mysql = require('mysql');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cookies;

var db = mysql.createConnection({
    host: 'hostname',
    user: 'username',
    password: 'password',
    database: 'database',
    port: 3306
});
db.connect(function(err){
    if (err) console.log(err)
        });

function createCookie(name,value,days, socket) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    socket.handshake.headers['cookie'] = name+"="+value+expires+"; path=/";
}

function readCookie(name, socket) {
    var nameEQ = name + "=";
    var ca = socket.handshake.headers['cookie'].split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name, socket) {
    createCookie(name,"",-1, socket);
}

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
    socket.on('chat message', function(msg){
        if(readCookie('uid', socket) != null) {
            db.query('SELECT * FROM ww_user_settings WHERE usr_set_id = '+readCookie('uid', socket)+' AND usr_set_setting_id = 23').on('result', function(data){console.log('Message from '+data.usr_set_value+': '+msg);io.emit('chat message', data.usr_set_value+": "+msg);});
        }
        else {
            console.log('Unauthorized message sent.');
            socket.disconnect('unauthorized');
        }
    });
});

http.listen(44444, function(){
    console.log('listening on *:44444');
});

正如我所说,Socket有效。但过了一段时间,即使没有什么特别的事情发生,Socket也会停止在我的Windows 2012 Server上运行。

1 个答案:

答案 0 :(得分:0)

这里的问题是服务器丢失了与MySQL服务器的连接。失去它,它将停止工作。