websocket handshake unexpected response code 404问题

The websocket handshake unexpected response code 404 problem occurs on the websocket client of the Html page, usually because the address is wrong. In new WebSocket(), you need to bring the deployed service name.

websocket = new WebSocket("ws://localhost:8080/access-web/websocket"); where access-web is the service name

<script type="text/javascript">
var websocket = null;
//Determine whether the current browser supports WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/access-web /websocket");
}
else {
alert('The current browser does not support websocket')
}

//Callback method for connection error
websocket.onerror = function () {
setMessageInnerHTML("WebSocket connection error");
};

//Callback method for successful connection establishment
websocket.onopen = function () {
setMessageInnerHTML("WebSocket connection is successful");
}

//Callback method for receiving messages
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}

//Connection close callback method
websocket.onclose = function () {
setMessageInnerHTML("WebSocket connection closed");
}

//Listen to the window closing event, when the window is closed, take the initiative to close the websocket connection to prevent the window from being closed before the connection is disconnected, and the server side will throw an exception.
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();
}

//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325213274&siteId=291194637