Joseph Webber
Joseph Webber

Reputation: 2173

socket.io client not receiving broadcasts from server

I have an instant messaging chat application in the making, and am having problems getting my client to receive data from my server. Could anyone explain to me why this is happening?

app.js

var http = require("http");
var express = require("express");
var socket = require("socket.io");

var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);

io.sockets.on("connection", function(client) {
    client.on("join", function(name) {
        client.set("nickname", name);
        console.log(name + " connected."); // logs name correctly
        client.broadcast.emit("names", name);
    });
});

index.html

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="/socket.io/socket.io.js"></script>
        <script type="text/javascript">
            var server = io.connect("http://localhost:8080");

            server.on("connect", function(data) {
                nickname = "";
                while (nickname == null || nickname.trim() == "") {
                    nickname = prompt("Enter name");
                }
                server.emit("join", nickname);
            });

            server.on("names", function(data) {
                document.getElementById("txtNames").value = data;
            });
        </script>
    </head>
    <body>
        <textarea id="txtNames"></textarea>
    </body>
</html>

Upvotes: 1

Views: 2319

Answers (1)

M Omayr
M Omayr

Reputation: 1351

Do you know what a broadcast is? When you broadcast a message as a result of an event from a socket, The message is emitted to all connected clients except for the socket who triggered the event. Same is your case. If you want to emit names event to your connected client then use

socket.emit("names", name); in your app.js

Upvotes: 2

Related Questions