使用node.js和socket.io进行私聊

时间:2017-01-26 15:22:33

标签: javascript socket.io

我尝试使用node.js和socket.io在密钥之间创建私人聊天, 问题是,当我发出一条消息时,该消息没有显示在房间里,我不知道是什么问题...

SERVER

 var app = require('express')();
    var express = require('express');
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    app.use(express.static('./public'));


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


    io.sockets.on('connection', function(socket){
        console.log("step 0 OK");                  // Works
     socket.on('room', function (room) {
        console.log("step 1 OK");                  // Works
            socket.join(room); 
      });
    });

    room = "1234";
//THIS CODE NOT WORKING
    io.sockets.in(room).emit('message', 'what is going on, party people?'); 


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

客户端

 $(document).ready(function() {

        var socket = io('http://localhost:3000');

        $("#triggerBtn").on("click", function(e) {
            e.preventDefault();

            socket.emit('room', '1234');
            return false;
        });


        socket.on('message', function(data) {
            console.log("Step 2 OK");               //THIS CODE IS NOT EXECUTED
        });




    });

HTML

<html>

<head>

    <title>Bootstrap Case</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>

</head>

<body>

    <div class="container-fluid">
        <li><a href="#"><button type="button" class="btn btn-default" id="triggerBtn">Enviar</button></a></li>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="./bootstrapPage.js"></script>

</body>

</html>

1 个答案:

答案 0 :(得分:4)

没有连接,套接字无法发出。移动:

io.sockets.in(room).emit('message', 'what is going on, party people?'); 

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