Game Development Reference
In-Depth Information
Listing 9-16. Setting Up the WebSocket Server
// Creates an HTTP server that will respond with a simple blank page when accessed.
var HTTPServer = HTTP.createServer(
function(Request, Response)
{
Response.writeHead(200, { "Content-Type": "text/plain" });
Response.end();
}
);
// Starts the HTTP server on port 9001.
HTTPServer.listen(9001, function() { System.log("Listening for connections on port
9001"); });
// Creates a WebSocketServer using the HTTP server just created.
var Server = new WebSocketServer(
{
httpServer: HTTPServer,
closeTimeout: 2000
}
);
Tip Generally, ports 0-1023 are reserved for system processes, but you are free to
choose any higher numbered port for your WebSocket server. In this case, we arbitrarily
choose 9001. Make sure that the port you choose is not being blocked by a firewall.
It's really that simple (on our end—of course there is some heavy stuff going on behind the scenes). If
we were to run this code, we would have a working WebSocket server at this point. It wouldn't do anything,
but it would be there. The next thing we do is subscribe to the WebSocket server's request event, which is
raised when somebody connects to the server. When that happens, we want to add that client to the
Connections object and then throw them into the fray with a bumper car. Actually, we'll put off giving the
new player a car until he sends a handshake message with an in-game handle, but more on that in
a minute.
Listing 9-17. Reacting to Clients Connecting to WebSocket Server
// When a client connects...
Server.on("request",
function(Request)
{
if (ObjectSize(Connections) >= MaxConnections)
{
Request.reject();
return;
}
var Connection = Request.accept(null, Request.origin);
Connection.IP = Request.remoteAddress;
// Assign a random ID that hasn't already been taken.
 
Search WWH ::




Custom Search