Monday, 13 March 2017

Random chat with 2 users at same time (Socket.io)

I just started learning NodeJS and Socket.io ... Until now I have this demo code, from official socket.io site:

http://socket.io/demos/chat/

I am able to get the unique client's ID of each user (socket) which connects, I am still trying to figure out, How can I make my code to only connect with 1 random user at a time when somebody runs the application. I just want to make random chat like Omegle http://www.omegle.com/

Only 2 users should randomly connect and chat with each other till they re-run the app, if they come back they should get connected with someone else who is in the online queue.

What changes do I need to do to have a similar functionality?

Here is my code so far:

Code examples or guidance from an expert will be really helpful for a beginner like me.

chat.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var dir = __dirname+'/public'; // Path of the index.js but one dir further (public)
app.use(express.static(dir));
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

//socket.set("log level", 1);
var peoples = {};

var rooms = ['Lobby'];
io.sockets.on("connection", function (client) {

    client.on("join", function(name){
        client.broadcast.emit("update", name + " has joined the server.");
        client.name = name;
        client.room = 'Lobby';
        peoples[client.id] = name;
        client.join('Lobby');
        client.emit('chat', 'SERVER', 'you have connected to Lobby');
        client.broadcast.to('Lobby').emit('chat', 'SERVER', name + ' has connected to this room');
    });
function switchRoom(room){
    socket.emit('switchRoom', room);
}
    client.on('create', function(room) {
        rooms.push(room);
    });

    client.on("send", function(msg){
        //client.broadcast.emit("chat", people[client.id], msg);
        client.broadcast.to(client.room).emit('chat', peoples[client.id], msg);
    });

    client.on("typing", function(msg){
        client.broadcast.emit("typi", peoples[client.id]);
    });

    client.on("notTyping", function(msg){
        client.broadcast.emit("notTypi", peoples[client.id]);
    });

    client.on('switchRoom', function(newroom) {
        var oldroom;
        oldroom = client.room;
        client.leave(client.room);
        client.join(newroom);
        client.emit('update', 'SERVER', 'you have connected to ' + newroom);
        client.broadcast.to(oldroom).emit('update', 'SERVER', client.people + ' has left this room');
        client.room = newroom;
        client.broadcast.to(newroom).emit('update', 'SERVER', client.people + ' has joined this room');
        client.emit('update', rooms, newroom);
    });

    client.on('disconnect', function() {
        delete peoples[client.people];
        io.sockets.emit('update', peoples);
        client.broadcast.emit('update', 'SERVER', client.people + ' has disconnected');
        client.leave(client.room);
    });


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

contents from index.html

    <script>   
    var typing = false;
var timeout = undefined;

function timeoutFunction(){
  typing = false;
  socket.emit("notTyping","");
}

function onKeyDownNotEnter(){
  if(typing == false) {
    typing = true
    socket.emit("typing","user is typing");
    timeout = setTimeout(timeoutFunction, 5000);
  } else {
    clearTimeout(timeout);
    timeout = setTimeout(timeoutFunction, 5000);
  }

}
        var socket = io();
        $("#2").hide();
        $("#name").focus();
        $("form").submit(function(event){
            event.preventDefault();
        });
        $("#join").click(function(){
            var name = $("#name").val();
            if (name != "") {
                socket.emit("join", name);
                socket.emit('create', "room1")
                $("#login").detach();
                $("#2").show();
                $("#msg").focus();
                ready = true;
            }
        });
        $("#name").keypress(function(e){
            if(e.which == 13) {
                var name = $("#name").val();
                if (name != "") {
                    socket.emit("join", name);
                    ready = true;
                    $("#login").detach();
                    $("#2").show();
                    $("#msg").focus();
                }
            }
        });
        socket.on("update", function(msg) {
            if(ready)
                $("#msgs").append("<li style='list-style: none;background: #484747;color: #fff;padding: 15px;text-align: left;'>" + msg + "</li>");
        })
        socket.on("update-people", function(people){
            if(ready) {
                $("#people").empty();
                $.each(people, function(clientid, name) {
                    $('#people').append("<li>" + name + "</li>");
                });
            }
        });
function switchRoom(room){
    socket.emit('switchRoom', room);
}
        socket.on("chat", function(who, msg){
            if(ready) {
                $('#msgs').append('<div class="row msg_body" style="margin:0;margin: 15px 0 15px"><div class="booty col-md-6 col-xs-8" style="padding:0;text-align:left;margin:0 15px;border-radius: 0 10px 10px 0"><div class="messages mleft" style="background: #fff;color:rgba(0, 0, 0, 1);padding: 10px;border-radius: 0 10px 10px 0;"><p style="margin:10px"><strong>'+who+'</strong>: '+msg+'</p></div></div></div>');
                $('.spoken-response__text').scrollTop($('.spoken-response__text')[0].scrollHeight);
            }
        });
        socket.on("typi", function(who){
            if(ready) {
                $('#typer').html(who+" is typing...");
            }
        });
        socket.on("notTypi", function(who){
            if(ready) {
                $('#typer').html("ExoChat 1.0");
            }
        });
        socket.on("disconnect", function(){
            $("#msgs").append("<li><strong><span class='text-warning'>The server is not available</span></strong></li>");
            $("#msg").attr("disabled", "disabled");
            $("#send").attr("disabled", "disabled");
        });
        $("#send").click(function(){
            var msg = $("#msg").val();
            $('#msgs').append('<div class="row msg_body" style="margin:0;margin: 15px 0"><div class="useer col-md-6 col-xs-8" style="padding:0;float:right;text-align:left;margin:0 15px;border-radius: 10px 0 0 10px"><div class="messages mright" style="background-color: #dcf8c6;color: rgba(0, 0, 0, 1);padding: 10px;border-radius: 10px 0 0 10px;"><p style="margin:10px"><strong>you</strong>: '+msg+'</p></div></div></div>');
            socket.emit("send", msg);
            $('.spoken-response__text').scrollTop($('.spoken-response__text')[0].scrollHeight);
            $("#msg").val("");
        });
        $("#msg").keypress(function(e){
            if(e.which == 13) {
                var msg = $("#msg").val();
                $('#msgs').append('<div class="row msg_body" style="margin:0;margin: 15px 0"><div class="useer col-md-6 col-xs-8" style="padding:0;float:right;text-align:left;margin:0 15px;border-radius: 10px 0 0 10px;"><div class="messages mright" style="background-color: #dcf8c6;color: rgba(0, 0, 0, 1);padding: 10px;border-radius: 10px 0 0 10px;"><p style="margin:10px"><strong>you</strong>: '+msg+'</p></div></div></div>');
                socket.emit("send", msg);
                $('.spoken-response__text').scrollTop($('.spoken-response__text')[0].scrollHeight);
                $("#msg").val("");
            }else{
            onKeyDownNotEnter();
            }
        });


</script>

Thanks in advance.



via Incredible Saurav

No comments:

Post a Comment