Reputation: 3760
I followed the net tuts tutorial to build a simple chat application with socket and node, and now I'm trying to extend the app to allow people to play a game I've written, so I want to let people list the games available, but I can't seem to pass even a simple test array from server to client.
I'll let the code speak for itself:
Relevant Server Code:
var games = ["test"];
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('gameList', function (data) {
io.sockets.emit("games",games);
});
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
ClientSide:
window.games = [];
$("#listGames").click(function(){
socket.emit("gameList", function(data){
window.games = data;
})
})
So I console.log games before and after the button click, and it's always just an empty array, when in my head, it should contain the string "test"
.
So where did I go wrong?
Note: Added jQuery to the codebase even though the tutorial missed it.
Upvotes: 1
Views: 7363
Reputation: 91679
You are using socket.emit()
to attempt to receive data. That only sends data to the server. You need a games
event handler on your client to handle the event accordingly.
window.games = [];
$("#listGames").click(function() {
socket.emit('gameList');
});
socket.on('games', function (games) {
window.games = games;
});
The event handler for games
is what will fire when you execute io.sockets.emit('games', games);
on the server side.
Also make sure to always pass an object as the response over Socket.IO. Change the server-side code from : var games=[];
to var games={'games':[]};
or something similar.
Upvotes: 4