<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">Send message</button>
<hr/>
<button onclick="closeWebSocket()">Close WebSocket connection</button>
<hr/>
<div id="message"></div>
</body>
<script>
var websocket = null;
// determine if the current browser supports WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/wsServer");
}
else {
alert('The current browser does not support websocket')
}
// Callback method for connection error
websocket.onerror = function () {
setMessageInnerHTML("An error occurred with the WebSocket connection");
};
// Callback method for successful connection establishment
websocket.onopen = function () {
setMessageInnerHTML("WebSocket connection successful");
}
// Callback method for received message
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
// Callback method for closing the connection
websocket.onclose = function () {
setMessageInnerHTML("WebSocket connection closed");
}
// Listen to the window close event and actively close the websocket connection when the window is closed to prevent the window from being closed before the connection is broken, which will throw an exception on the server side.
window.onbeforeunload = function () {
closeWebSocket();
}
// Display the message on the web page
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//Close the WebSocket connection
function closeWebSocket() {
websocket.close();
}
//Send a message
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
Read More: