Game Development Reference
In-Depth Information
Let's look at the basic socket server implementation:
var io = require('socket.io').listen(400);
io.sockets.on('connection', function (socket) {
socket.on('any event', function(data) {
console.log(data);
});
});
The preceding code initializes a basic socket server and waits for requests at port
number 4000 . The primary event handler is attached to the connection event. Once
the server receives a connection request, it creates a socket object. The socket defines
an event on the arbitrary label, any event . When the client emits an event with the
any event label, this handler ( function (socket) ) is invoked. The label is just
created to differentiate different kinds of messages that a client sends.
Let's look at a basic Socket.IO client's code:
<html>
<head>
<title>Socket.IO example application</title>
<scriptsrc="http://localhost:400/js/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4000');
socket.emit('any event', 'Hello Game world.');
</script>
</head>
<body></body>
</html>
In the preceding code, we have included js/socket.io.js . In the code, we first
open a connection by invoking the io.connect function and then invoke the
socket.emit function with the any event label. Note that we have not used any
WebSocket API calls in the client code as the Socket.IO client library abstracts the
complete implementation.
Let's say that the preceding code was saved in index.html , but when we simply
double-click on the file, our code might not run as the WebSocket API can generate
security issues with local files. Hence, we would want this file to be rendered by our
web server. So, let's combine our WebServer and socket server to handle both types
of requests with the help of the following code:
var httpd = require('http').createServer(httphandler);
var io = require('socket.io').listen(httpd);
var fs = require('fs');
httpd.listen(400);
 
Search WWH ::




Custom Search