Game Development Reference
In-Depth Information
The following is the response from the server:
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: game
If you have noticed, the server switched protocols from HTTP to WebSocket.
Understanding the WebSocket API
We want to introduce some WebSocket API functions implemented by most
browsers. The following code opens a connection over a nonsecure port:
var connection = new WebSocket('ws://mygame.org:4000/game')
The wss protocol is for secure communication:
var connection = new WebSocket('wss://mygame.org:4000/game');
The second parameter, ['game'] , is a subprotocol to inform the server about the use
of the connection:
var connection = new
WebSocket('wss://mygame.org:4000/game',['game']);
The response handler when the connection is opened is shown in the following
code snippet:
connection.onopen = function(){
console.log('Congrats Connection opened!!!');
}
The response handler when the connection is closed is shown in the following
code snippet:
connection.onclose = function(){
console.log('Sorry Connection closed!!!');
}
To explicitly close the connection, use the following line of code:
connection.close();
The handler to handle any errors in connection is shown in the following code snippet:
connection.onerror = function(error){
console.log('Shit something went bad: ' + error);
}
 
Search WWH ::




Custom Search