1
votes

I am trying to create websocket connection between Chrome Browser and Glassfish 4.1.1 server. Unfortunately, I get HTTP 200 message instead of 101.

Chrome DevTool log:

"WebSocket connection to 'ws://DOMAIN_NAME:8080/serverendpointdemo/' failed: 
Error during WebSocket handshake: Unexpected response code: 200"

Client side code:

var ws = new WebSocket ("ws://" + document.location.host + "/serverendpointdemo/");

Server side code:

package com.za.tutorial.websocket;

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

@ServerEndpoint("/home/USER_NAME/glassfish4/glassfish/domains/domain1/applications/serverendpointdemo")
public class ServerEndpointDemo {
    @OnOpen
    public void handleOpen() {
        System.out.println("Client is now connected...");
    }

    @OnMessage
    public String handleMessage (String message) {
       return null;
    }

    @OnClose
    public void handleClose () {
    }

    @OnError
    public void handleError (Throwable t) {
        t.printStackTrace();
    }
}
1
I won it this way: Client side Javascript code: var ws = new WebSocket ("ws://DOMAIN_NAME:8080/serverendpointdemo/serverendpointdemo"); Helpful links, if elseone got it: link link link - Rinat
It is a feature of the Glassfish Server. In GlassFish, if your application is deployed with the contextroot mycontextroot in a Web container listening at port 8080 of localhost, the WebSocket will be accessible using ws://localhost:8080/mycontextroot/hello. Full text: link - Rinat

1 Answers

0
votes

serverside: @ServerEndpoint(value = "/ws") public class WebSocketConfig {

private String message = "";
private String to = "";
private String from = "";
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

@OnOpen
public void onOpen(Session session, EndpointConfig econfig) throws IOException {        
    System.out.println("New Web Socket Connection created");
    session.getBasicRemote().sendText("onOpen new socket connection");             
}

@OnClose
public void onClose(Session session) {     
        sessions.remove(session);
}

@OnMessage
public void onMessage(String message, Session session) throws IOException {

}

client side:

while making a connection you should specify the contextpath var ws = new WebSocket ("ws://" + document.location.host +"/"+your-contextPathName+"/serverendpointdemo/");

http: ws://hostname:port/contextpath/serverendpoint https: wss://hostname:port/contextpath/serverendpoint

ex: ws://document.location.host+"/WebsocketDemo/ws";