Websocket Front-end Call Example

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">Send message</button>
<button onclick="closeWebSocket()">Close WebSocket connection</button>
<div id="message"></div>
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) {

// 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 () {
// Display the message on the web page
function setMessageInnerHTML(innerHTML) {
	document.getElementById('message').innerHTML += innerHTML + '<br/>';
//Close the WebSocket connection
function closeWebSocket() {
//Send a message

function send() {
var message = document.getElementById('text').value;


Read More: