Creating your first WebSocket client
In this recipe, we will create a simple client to start the WebSocket handshake process. The client will send a pretty standard HTTP GET
request to the WebSocket server and the server upgrades it through an Upgrade header in the response.
How to do it…
- Create
index.html
where we will open a connection to a non-secure WebSocket server on page load, as follows:
<html> <title>WebSocket Server</title> <input id="input" type="text" /> <button onclick="send()">Send</button> <pre id="output"></pre> <script> var input = document.getElementById("input"); var output = document.getElementById("output"); var socket = new WebSocket("ws://" + window. location.host + "/echo"); socket.onopen = function () { output.innerHTML += "Status: Connected\n"; }; socket.onmessage = function (e) { output.innerHTML += "Message from Server: " + e.data + "\n"; ...