Friday, 7 April 2017

Broadcast in socket.io

I am trying to do an excercise in socket.io. In my case it should be a green circle and a button. If I click on the button, circle in my browser should become blue, but in another browsers it should became orange.

But in my case something wrong happens. In my browser it becomes blue, but the button disappears. In another browsers nothing happens.

My client code:

    <style>
    .circle {
        width: 100px;
        height: 100px;
        background: green;
        border-radius: 50%;
        display: block;
    }
</style>

<div class = "circle" id = "circle"></div>
<button id = "blue">Blue</button>

<script src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js">
</script>

<script>
    var socket = io("http://localhost:8000");
    var circle = document.getElementById("circle");
    var blue = document.getElementById("blue");

    socket.on("color", function(color){
        socket.style.background = color;
    })

    blue.addEventListener ("click", function(){
        circle.style.background = "blue";
        socket.emit("color", "blue");
        blue.style.display = "none";
    })
</script>   

My server code:

var app = require('http').createServer()
var io = require("socket.io")(app)

app.listen(8000)

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

    socket.on ("color", function(){
        socket.broadcast.emit("color", "orange");
    })

    socket.on("disconnect", function(){
        console.log("1 client disconnected");
    })
})

Where's my mistake? What do I do wrong?



via Aleks339

No comments:

Post a Comment