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: 'wele 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.
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: 'wele 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.
Share Improve this question edited Sep 16, 2013 at 16:03 hexacyanide 91.9k31 gold badges166 silver badges162 bronze badges asked Sep 16, 2013 at 15:59 Jason NicholsJason Nichols 3,7603 gold badges32 silver badges51 bronze badges1 Answer
Reset to default 4You 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.