Skip to content

Developing with WebSockets

CaffeinatedRat edited this page Mar 2, 2013 · 1 revision

Check if a browser supports WebSockets

You can check if a browser supports the WebSockets protocol by seeing if the window object contains the property "WebSocket"

if ("WebSocket" in window) {

     console.log('This browser supports WebSockets');

}
else {

     console.log('This browser does NOT supports WebSockets');

}

Using the Javascript WebSocket object.

The following snippet of code provides a very simple example of how to use the Javascript WebSocket object. Note that the close method is not used in the sample below. This is due to the fact that almost all of the services provided by the WebSocketServices plug-in automatically terminates the connection once the information is sent. This is to keep the number of connections to the minecraft server at a minimum. You can find more information about using the WebSocket object at the following links:

If you'd like more in depth information about WebSockets, visit the link below.

//Create your websocket object at the specific address.
var ws = new WebSocket('ws://Myaddress:port');

//This function is called when the websocket connection has been established.
ws.onopen = function () {

	ws.send('Message to Send');

};

//This function is called when a message is received by the client.
ws.onmessage = function (msg) {

	if (msg !== undefined) {

		var data = msg.data;

	}
	//END OF if(msg !== undefined) {...

};

//This function is called when the connection is terminated.
ws.onclose = function () {


}

//This function is called whenever there is an communication error.
ws.onerror = function (error) {

	console.log('WebSocket Error ' + error);

};

Clone this wiki locally