1

Below is the code for socket.

package com.shankar.rest;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/** 
 * @ServerEndpoint gives the relative name for the end point
 * This will be accessed via ws://localhost:8080/com.shankar.rest/echo
 * Where "localhost" is the address of the host,
 * "com.shankar.rest" is the name of the package
 * and "echo" is the address to access this class from the server
 */
@ServerEndpoint("/echo") 
public class EchoServer {
    /**
     * @OnOpen allows us to intercept the creation of a new session.
     * The session class allows us to send data to the user.
     * In the method onOpen, we'll let the user know that the handshake was 
     * successful.
     */
    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId() + " has opened a connection"); 
        try {
            session.getBasicRemote().sendText("Connection Established");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * When a user sends a message to the server, this method will intercept the message
     * and allow us to react to it. For now the message is read as a String.
     */
    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("Message from " + session.getId() + ": " + message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * The user closes the connection.
     * 
     * Note: you can't send messages to the client from this method
     */
    @OnClose
    public void onClose(Session session){
        System.out.println("Session " +session.getId()+" has ended");
    }
}

Am not sure why it throwing error when connect with JavaScript.

<!DOCTYPE html>

<html>
<head>
<title>Echo Chamber</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>

    <div>
        <input type="text" id="messageinput" />
    </div>
    <div>
        <button type="button" onclick="openSocket();">Open</button>
        <button type="button" onclick="send();">Send</button>
        <button type="button" onclick="closeSocket();">Close</button>
    </div>
    <!-- Server responses get written here -->
    <div id="messages"></div>

    <!-- Script to utilise the WebSocket -->
    <script type="text/javascript">

            var webSocket;
            var messages = document.getElementById("messages");


            function openSocket(){
                // Ensures only one connection is open at a time
                if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
                   writeResponse("WebSocket is already opened.");
                    return;
                }
                // Create a new instance of the websocket
                webSocket = new WebSocket("ws://localhost:8080/com.shankar.rest/echo");

                /**
                 * Binds functions to the listeners for the websocket.
                 */
                webSocket.onopen = function(event){
                    // For reasons I can't determine, onopen gets called twice
                    // and the first time event.data is undefined.
                    // Leave a comment if you know the answer.
                    if(event.data === undefined)
                        return;

                    writeResponse(event.data);
                };

                webSocket.onmessage = function(event){
                    writeResponse(event.data);
                };

                webSocket.onclose = function(event){
                    writeResponse("Connection closed");
                };
            }

            /**
             * Sends the value of the text input to the server
             */
            function send(){
                var text = document.getElementById("messageinput").value;
                webSocket.send(text);
            }

            function closeSocket(){
                webSocket.close();
            }

            function writeResponse(text){
                messages.innerHTML += "<br/>" + text;
            }

        </script>

</body>
</html>

When I try to open connection from JavaScript, it throws the following error:

WebSocket connection to 'ws://localhost:8080/com.shankar.rest/echo' failed: Error during WebSocket handshake: Unexpected response code: 404

Here is my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Demo</display-name>
  <welcome-file-list>
    <welcome-file>NewFile.html</welcome-file>
  </welcome-file-list>

  <servlet>
      <servlet-name>SimulationAPI</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
      <init-param>
           <param-name>jersey.config.server.provider.packages</param-name>
           <param-value>com.shankar.rest</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SimulationAPI</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>
  • How is this question different than your prior question from a few hours ago which you got comments and an answer for, but did not respond to http://stackoverflow.com/questions/38747699/socket-server-not-connect-with-javascript-socket-client – jfriend00 Aug 03 '16 at 19:57
  • 2
    If you did not understand something in the answer I provided to your previous question, then you should post a comment to that answer and explain exactly what you don't understand. You don't just keep posting the same question here over and over again, hoping for another answer. That is against the rules. If you do post an additional question, it should be very clear how it is different than your prior question. And, if someone provides you an answer you don't understand, ask them about it by posting comments to their answer. – jfriend00 Aug 03 '16 at 20:34
  • How did you deploy your class to server ? – Sanjeev Aug 04 '16 at 06:11

0 Answers0