Game Development Reference
In-Depth Information
function httphandler(req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading File');
}
res.writeHead(200);
res.end(data);
}
);
}
io.sockets.on('connection', function (socket) {
socket.on('clientData', function(data) {
socket.emit('serverData', data);
socket.broadcast.emit('serverData', socket.id +content);
});
});
The preceding code first creates an HTTP server object. It then creates a socket
server object and binds itself to the HTTP server port ( require('socket.io').
listen(httpd); ). Now, the socket and web servers are listening at the same
port number.
The HTTP server defines a request handler, httphandler , and reads the file
index.html . If an error occurs while reading, then it sets the HTTP response status
header to 500 and sets response content to an error message. If no error occurs, it
writes the file content to the response.
The socket server implementation introduces us to a new server-side function,
socket.broadcast.emit('serverData', socket.id +content) . This
server-side function sends the data to all the clients connected to the socket server
(except the socket it is fired on) with the client event, serverData . Let's just
understand the sequence of events.
The following client code defines the client handler function for the server event,
serverData . It simply logs the received data. When the Enter key is pressed, it sends
the data to the socket with the clientData event:
var socket = io.connect('http://localhost:400');
socket.on('serverData', function(content) {
console.log(content);
}
var inputElement = document.getElementById('input');
inputElement.onkeydown = function(keyboardEvent) {
if (keyboardEvent.keyCode === 13) {
 
Search WWH ::




Custom Search