聊天应用。使用express和socket.io

时间:2014-08-20 05:00:00

标签: node.js express socket.io

我有一个群聊应用。当客户使用他的电子邮件和密码登录时,他将被引导到他的名字在顶部的聊天页面,他将能够与在线用户聊天。我的应用程序如何。确定从哪个用户消息发送。一种可能性是将socket.id和消息一起发送到服务器以识别用户但socket.id在刷新页面时得到更改。

login.html

<!DOCTYPE html>
<html>
<head>  
  <link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
  <form  class="css" method="post" action="http://192.168.1.3:9373/valid" >
    <fieldset >
      <input type="text" name="email" class="inputemail"  placeholder="Email" />
    </fieldset> 
    <fieldset >
      <input type="password" name="pass" class="inputpassword" placeholder="Password" />
    </fieldset >
    <fieldset >
      <button type="submit" class="submit">Submit</button>
    </fieldset>
  </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="/socket.io/socket.io.js"></script>

    <script type="text/javascript">

      var socket = io.connect('http://192.168.1.3:9373');

    </script>
</body>
</html>

chat.html

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <div class="name"> Welcome </div>
    <br></br>
    <div class="chat"></div>

    <form>
        <input type="text" class="msg"> </input>
        <button type="submit" class="enter">Send</button>
        <input type="file" class="file"></input>
    </form>

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
    var socket = io.connect('http://192.168.1.3:9373');
    var online=[];
    var checkFile=0;

    $.get("/getName", function(string){
        username=string;
        $('.name').append(username);
    });

    $('.enter').bind("click",function(){

        $.get("/getMsg", function(){
            setTimeout (function(){
                socket.emit('chat message',$('.msg').val() );
                $('.msg').val('');
            },0);
        });       

        return false;
    });


        socket.on('chatmessage', function(name,msg){

            var block= $("<div class='message'> </div>");

            if(msg.length){
                var messenger= $("<div class='messenger'> </div>");

                messenger.append(name);
                block.append(messenger);
                var text;
                text=$("<div class='text'></div>");
                text.append(msg);
                block.append(text);
                block.append($("<div class='pad'></div>"));
                $('.chat').append(block);  
            }
        });    

});
</script>
</body>
</html>

server.js

var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, sessionStore = session.MemoryStore()
, async = require('async')
, mysql = require("mysql");

var id=[];
var a;

server.listen(9373,'192.168.1.3');

app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser("secret"));

app.use(session({
   store: sessionStore,
   secret: "54321",
   saveUninitialized: true,
   resave: true
}));

app.get('/loginme', function (req, res) {
  res.sendfile(__dirname + '/loginmysql.html');
});

app.get('/option', function (req, res) {
  res.sendfile(__dirname + '/option.html');
});

app.get('/getName', function (req, res) {
  var r = {};
  r.name = req.session.userid;
  res.send(r.name);
});


app.get('/getMsg', function (req, res) {
  a = req.session.id;
  res.json(a);
});

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


app.post('/valid', function (req, res) {

  var username=req.body.email;
  var password=req.body.pass;

  var connection = mysql.createConnection({
    "hostname": "localhost",
    "user": "root",
    "password": "vk123",
    "database": "login"
  });

  connection.connect();

  connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){

    if (err){
      throw err;
    }else{

      var name=rows[0].name;
      req.session.userid =  name;
      id.push({sid:req.session.id, username:req.session.userid});
      res.redirect('http://192.168.1.3:9373/option'); 
      io.sockets.on('connection', function (socket){
        io.emit('name',name);
      });     
    }
  });

  connection.end();

});



  io.sockets.on('connection', function (socket){


    socket.on('chat message', function(msg){
      var user;
      var i;
      for(i=id.length-1; i>=0; i--){
        if(id[i].sid == a){
          user=id[i].username;
          break;
        }
      }
      io.emit('chatmessage',id[i].username,msg);      
    });

  });

app.use(express.static(__dirname+'/public'));

0 个答案:

没有答案