WebSockets – Closing a Connection
”;
Close event marks the end of a communication between the server and the client. Closing a connection is possible with the help of onclose event. After marking the end of communication with the help of onclose event, no messages can be further transferred between the server and the client. Closing the event can occur due to poor connectivity as well.
The close() method stands for goodbye handshake. It terminates the connection and no data can be exchanged unless the connection opens again.
Similar to the previous example, we call the close() method when the user clicks on the second button.
var textView = document.getElementById("text-view"); var buttonStop = document.getElementById("stop-button"); buttonStop.onclick = function() { // Close the connection, if open. if (socket.readyState === WebSocket.OPEN) { socket.close(); } }
It is also possible to pass the code and reason parameters we mentioned earlier as shown below.
socket.close(1000, "Deliberate disconnection");
The following code gives a complete overview of how to close or disconnect a Web Socket connection −
<!DOCTYPE html> <html> <meta charset = "utf-8" /> <title>WebSocket Test</title> <script language = "javascript" type = "text/javascript"> var wsUri = "ws://echo.websocket.org/"; var output; function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen(''<span style = "color: blue;">RESPONSE: '' + evt.data+''</span>''); websocket.close(); } function onError(evt) { writeToScreen(''<span style = "color: red;">ERROR:</span> '' + evt.data); } function doSend(message) { writeToScreen("SENT: " + message); websocket.send(message); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false); </script> <h2>WebSocket Test</h2> <div id = "output"></div> </html>
The output is as follows −
”;