如何使用Websockets实现Socket.io聊天应用程序并从数据库中获取用户名(mysqli)

时间:2017-06-21 11:19:59

标签: javascript php node.js mysqli socket.io

我正在寻找一种实现聊天功能的方法,

我正在为残障人士建立一个约会/友谊网站,它很顺利。

因为我是编程领域的初学者,所以我一直在寻找一种方法来创建一个简单的聊天功能(理想情况下只有在相互喜欢或感兴趣时才能运行),所以我在youtube上发现了一个 - [ https://www.youtube.com/watch?v=tHbCkikFfDE],完美,无页面重装等。

当它在Localhost:3000上打开时它就像一个魅力,但是我尝试将它实现到我的网站并显示,但不起作用,此聊天也有登录功能,但考虑到当客户端在我的网站上他们已经登录。我想知道如何获取我的用户数据,然后将其用于聊天。

chat.php文件

     <!DOCTYPE html>
      <html>
   <head>
  <title>chat</title>




      <link rel = "stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/
     3.3.6/css/bootstrap.min.css">
 <script src="https://code.jquery.com/jquery-latest.min.js"></script>
 <script src="/socket.io/socket.io.js"></script>
  <style >
  body{ margin-top: 5em;
       }

  </style>
  </head>
   <body>
<div class = "container">

 <div id = "userFormArea" class= "row">
 <div class = "col-md-12">
  <form id = "userForm">
   <div class = "form-group">
    <label>Enter Username</label>
    <input class = "form-control" id = "username">
    <br/>
    <input type="submit" class = "btn btn-primary" value = " Login"/>
   </div>
   </form>

 </div>
 </div>
 <div class = "row" id = "messageArea">
<div class = "col-md-4">
 <div class = "well">
   <h3> Online users </h3>
  <ul class = "list-group" id = "users"> </ul>

  </div>

</div>
<div class = "col-md-8">
<div class="chat" id = "chat"> </div>

 <form id = "messageForm">
  <div class = "form-group">
  <label>Enter Message</label>
  <textarea class = "form-control" id = "message"> </textarea>
  <br/>
   <input type="submit" class = "btn btn-primary" value = "Send Message"/>
  </div>
   </form>
   </div>

 </div>

 </div>
 <script>
   $(function(){
  var socket = io.connect();
 var $messageForm = $('#messageForm');
 var $message = $('#message');
 var $chat = $('#chat');
  var $userFormArea = $('#userFormArea');
  var $userForm = $('#userForm');
  var $messageArea = $('#messageArea');
    var $users = $('#users');
  var $username = $('#username');

  $messageForm.submit(function(e){
   e.preventDefault();
   socket.emit('send message', $message.val());
   $message.val('');
  });

  socket.on('new message', function(data){
     $chat.append('<div class = "well"><strong>'+data.user+'</strong>:' + 
  data.msg + '<div>');
   });

  $userForm.submit(function(e){
   e.preventDefault();
    socket.emit('new user', $username.val(),function(data){
    if(data){
    $userFormArea.hide();
     $messageArea.show();
    }
    });
   $username.val('');
  });
  socket.on('get users', function(data){
  var html = '';
  for (i = 0; i< data.length; i++){
    html +='<li class = "list-group-item" >' + data[i]+ '</li>';
    }
     $users.html(html);
   });
  });
 </script>

server.js文件

var express =require('express'),
  http = require('http');
 var app= express();
 var server = require('http').createServer(app);
 var io = require('socket.io').listen(server);

 users = [];
 connections = [];

  server.listen(process.env.Port || 3000);
  console.log('server running ...')

 app.get('/', function(req, res) {
  res.sendFile(__dirname + '/chat.php');
  });

 io.sockets.on('connection', function(socket){
   connections.push(socket);
  console.log('Connected: %s sockets connected', connections.length);

   socket.on('disconnect',function(data){
   users.splice(users.indexOf(socket.username),1);
   updateUsernames();
  connections.splice(connections.indexOf(socket),1);
   console.log('Disconnected: %s sockets conected', connections.length);
  } );
  //send message
  socket.on('send message', function(data){
   console.log(data)
   io.sockets.emit('new message',{msg: data, user: socket.username});
    });

  //new User

   socket.on('new user', function(data,callback){
   callback(true);
   socket.username = data;
   users.push(socket.username);
    updateUsernames();
    });

     function updateUsernames(){
     io.sockets.emit('get users', users)
    }
    });

原谅长篇文章,我将继续在互联网上寻找答案,所以也许我可以使这个问题更具体。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我会告诉你mysql变种它非常相似。

首先,您需要一些额外的模块来完成这项工作:

    var CONFIG = require('./config');
    var dl  =            require('delivery');
    var fs  =            require("fs");
    var mysql =          require('mysql');
    var express =    require("express");
    var app =            express();
    var http =           require('http');
    var https =      require('https');
    var mkdirp =       require('mkdirp');
    var nodemailer = require('nodemailer');
    function include(f) {eval.apply(global, [read(f)]);}
    function read(f) {return fs.readFileSync(f).toString();}

从npm安装定义中的所有模块。

var REG_PATH = CONFIG.PATH_OF_WWW + CONFIG.REG_PATH; 

include('lib/preinit.js');

var DATABASE = require('./account/account');

DATABASE.fs = fs;
DATABASE.handleDisconnect();
DATABASE.GET_ALL_USERS();

// NO SECURE - HTTP 

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(CONFIG.ACCOUNT_PORT);
console.log('Socket server listening on port : ' , CONFIG.ACCOUNT_PORT);

接下来是套接字作业,但您可以在address找到完整的文件。

我会展示您的小型自定义模块(需要(&#39; ./ account / account&#39;)):

重要:不要错过这个功能:&#34; this.connection.on(&#39;错误&#39; ...&#34;

module.exports = {

NAME : 'account_system',

// EMAIL SYSTEM CONFIG
smtpTransport : require('nodemailer').createTransport("SMTP",{
host: "smtp.gmail.com", // hostname
secureConnection: false,
port: 587, // port for secure SMTP
requiresAuth: true,
domains: ["gmail.com", "googlemail.com"],
tls: {ciphers:'SSLv3'},
auth: {
user: "eroulete@gmail.com",
pass: "###"
}
}),

fs : '',

createEmailVerifyFile : function(path_ , script_inner){
    //fs.writeFile( "../www/html/users/" + path_ , "<html><head><script src='../../js/socket.io.js'></script><script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script></head><body> <h1> Cool... </h1><script>"+script_inner+"</script> </head></body>", function(err) {
    this.fs.writeFile(  path_ , "<html><head><script src='../../lib/io/socket.io.js'></script><script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script></head><body> <h1> Cool... </h1><script>"+script_inner+"</script> </head></body>", function(err) {

    if(err) {
        return console.log(err);
    }else
    {
    console.log("The file was saved!");
    }
});  

},

SEND_EMAIL : function( sub_ , to , plain ) {

this.smtpTransport.sendMail({
   from: "Maximumroulette.com <eroulete@gmail.com>", // sender address
   to: "New user <"+to+">", // comma separated list of receivers
   subject: sub_, // Subject line
   html: plain // plaintext body
}, function(error, response){
   if(error){
       console.log("error in sending email" , error);
   }else{
       console.log("Message sent : " + response.message);
   }
});

},


//Database 
connection : require('mysql').createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'nikola',
  database : 'test'
}), 

handleDisconnect : function(){

  this.connection = require('mysql').createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'nikola',
  database : 'test'
}); 
    this.connection.connect(function(err){

if(!err) {

    console.log("Init..................... \n");  
    console.log("Database is connected ... \n");

} else {
    console.log("Error connecting database... \n" , err);  
}
});
    /////////////////////////////////////////////////////////////////////////

    this.connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
     setTimeout(function(){ this.handleDisconnect();    },500);                     // lost due to either server restart, or a
    } else { 
    // connnection idle timeout (the wait_timeout
    console.log('db error BIG', err);
    this.connection.end();
    setTimeout(function(){ this.handleDisconnect();    },500);                     // lost due to either server restart, or a

   //  throw err;                                  // server variable configures this)
    }
  });


},


GET_ALL_USERS : function(){

this.connection.query('SELECT * from accounts', function(err, rows, fields) {
  if (!err){
    console.log(' GET ALL USERS : ', rows);
    ACCOUNTS.LIST = [];
    ACCOUNTS.INSERT(rows);

    }
  else
  {
    console.log('Error while performing Query.');
  }
});

},

// New account
//var NEW_ACCOUNT_POST = {   password: "nidza" , email:"zlatnaspirala@gmail.com" ,  token : token() };


ADD_NEW_ACCOUNT : function(post) {
var query = this.connection.query('INSERT INTO accounts SET ?', post, function (err, result) {});
console.log(query.sql);
},
//ADD_NEW_ACCOUNT(NEW_ACCOUNT_POST);


ACTIVATE_ACCOUNT : function(post) {

this.connection.query('UPDATE accounts SET active = ? WHERE token = ?', [post.active , post.token ]  ,  function (err, result) {

if (!err) {

console.log("ACTIVATE ACCOUNT");

}

});

},


SET_NEW_NICKNAME : function(post, email) {
var query = this.connection.query('UPDATE accounts SET nickname=? WHERE email=?', [post, email] , function (err, result) {
 if (!err){
 console.log("add new nickname evenk OK"); 
 }
 else {
 console.log("add new nickname event ERROR "); 
 }

});
},

//Session 
SETUP_SESSION : function(post) {
this.connection.query('UPDATE accounts SET online = ? WHERE token = ?', [ "yes" , post ] , function (err, result) {
console.log(post);
if (!err) {
console.log("setup session OK online = yes for token " , token);
}
else {
console.log("error in setup session");
}
});
},  

CLOSE_SESSION : function(post , ID) {

this.connection.query('UPDATE accounts SET online = ? WHERE token = ?', [ "no" , post ] );
this.connection.query('DELETE FROM level1 WHERE email = ?', [ ID ] , 
 function(err , result){
 if (!err) {

 console.log("player deleted from active games in level1 ");

 }else{

 console.log("player deleted from active games in level1 ERROR IN ");

 }

 });
//console.log(query.sql);
},

// New room
//var ADD_ROOM_POST = {   id : "0" , game:"level1 room " ,  accesstoken : token() , wager : 0.1 , maxbet : 50  };
//ADD_NEW_ROOM(ADD_ROOM_POST);

ADD_NEW_ROOM : function(post) {
var query = this.connection.query('INSERT INTO rooms SET ?', post, function (err, result) {
 if (!err){

 console.log("add new room evenk OK"); 

 }
 else {

 console.log("add new room evenk ERROR : Maybe room already exist."); 

 }


});
},


LOAD_ROOMS : function(post) {
var query = this.connection.query('SELECT * FROM rooms', function (err, rows, fields) {

  if (!err){

    console.log('ROOM  list : ', rows);
    ROOMS.INSERT(rows);

    }
  else
  {
    console.log('Error while performing Query : load rooms' , err);
  }

});

},

};