简体   繁体   中英

Private chat using node.js and socket.io

Im tryng to create a private chat between a key using a node.js and socket.io, the problem is when i emit a message, that message is not displayed on the room, and i dont know what is the problem...

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');
    });

CLIENT

 $(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>

Sockets can't emit without a connection. move:

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

inside:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM