Using WebSockets without Socket.io


#1

Upcoming book on MMOG Development. Created by a Cisico Certified Academy Instructor for the past 14years with 37 years of WAN experience, and 14 years teaching at university level software engineering, network security and game development. Here’s a snippet of JS I use to launch WebSockets without all the overhead in Socket.io.


<!-- Creating Client WebSocket -->
<script >
	function WebSocketTest() {
		if ("WebSocket" in window) {
			alert("WebSocket is supported by your Browser!");
			// Let us open a web socket on local development site;

			//TODO: Change the URL to point to your live production server.
			//Classic OOP style creates object/function:
			var ws = new WebSocket("ws://localhost:9998/echo");

			//OLOO style; note that false warning
			//var ws = Object.create(WebSocket("ws://localhost:9998/echo"));

			//
			//============================
			// 4 WebSocket Protocol Msg
			//============================
			ws.onopen = function onopen(event)
			{
				// Web Socket is connected, send data using send()
				ws.send("Test Message sent");
				alert("Test Message away, away ... Captain!");
			};
			ws.onmessage = function onmessage(event) 
			{ 
				var received_msg = event.data;
				alert("Incoming Messages ... brace for impact, Captain!");
			};
			ws.onclose = function onclose()
			{ 
				// websocket is closed.
				alert("Connection is closed..."); 
			};
			//============================
			// End of WebSocket Protocol
			//============================
		} else {
			// The browser doesn't support WebSocket
			alert("WebSocket NOT supported by your Browser!");
		}
	}
</script>

Demonstration is here:
PBMCube MMoG Demo

Perhaps my illustrations might help; it comes from
Multiplayer Game Systems