Forewarning, I'm a newcomer to Javascript, node.js, socket.io. It's been pretty amazing so far. :)
I am trying to create a simple username interface at the moment. Client will enter in their username of choice, click the button and will fire an event that will send the username to the server to be put into an array.
Client connects fine, handshake occurs. Yet the socket isn't emitting the data to the server.
Server:
var io = require('socket.io').listen(8888);
var players = [];
io.sockets.on('connection', function (socket) {
socket.on('adduser', function(username) {
players.push(username);
console.log("Received: " + username);
});
});
Client:
var socket = io.connect('/socket.io/socket.io.js');
function usernameSubmit(){
console.log("Button pressed");
var textfield = document.getElementById('usernamefield');
var username = textfield.value
if (username != ""){
console.log(username);
socket.send('adduser', username);
console.log("Username submitted.");
}
else
console.log("Blank username detected.");
}
Thanks for the help!
You should use .emit instead. That way you can pass an object and access it on the server.
Client:
if (username != ""){
console.log(username);
socket.emit('adduser', { username: username });
console.log("Username submitted.");
}
Server:
socket.on('adduser', function(data) {
players.push(data.username);
console.log("Received: " + data.username);
});