Question

I'm trying to create a simple Websocket connection in my project.

Java code:

@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session,String message){
    try{
        System.out.println(message);
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
}

}

html and javascript code:

<button type="button" onclick="WebSocketTest()">Send</button>
<script type="text/javascript">
function WebSocketTest()
{

 alert("WebSocket is supported by your Browser!");
 // Let us open a web socket
 var ws = new WebSocket("ws://localhost:8080/echo");
 ws.onopen = function()
 {
    // Web Socket is connected, send data using send()
    ws.send("Message to send");
    alert("Message is sent...");
 };
 ws.onmessage = function (evt) 
 { 
    var received_msg = evt.data;
    alert("Message is received...");
 };
 ws.onclose = function()
 { 
    // websocket is closed.
    alert("Connection is closed..."); 
 };


 }
 </script>

after pressing the button I got the errorWebSocket connection to 'ws://localhost:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 404

Jboss Wildfly8 is used as Application Server.

Any Idea? or any working example?

Was it helpful?

Solution

This is because you put wrong path here:

var ws = new WebSocket("ws://localhost:8080/echo");

if your application is packed to eg: websocketapp.war (or if you set context-path on websocketapp) then you should use:

var ws = new WebSocket("ws://localhost:8080/websocketapp/echo");

OTHER TIPS

Connecting to web-socket For example

var webSocket= new WebSocket("ws://l92.168.1.27:50333/project name//serverendpointdemo");

    var messagesTextArea=document.getElementsByClassId("messagesTextArea");
    webSocket.onopen=function(message){processOpen(message);};
    webSocket.onclose=function(message){processClose(message);};
    webSocket.onmessage=function(message){processMessage(message);};
    webSocket.onerror=function(message){processError(message);};
    function processOpen(message){
        messagesTextArea.value+="Server connected...."+"\n";
    }
    function processMessage(message){
        messagesTextArea.value+="Received from server:...."+message.data+"\n";
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top