Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket example won't work

I try run this example:

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/chat")
public class ChatServer {

    private static final Logger LOGGER = 
            Logger.getLogger(ChatServer.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "New connection with client: {0}", 
                session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}", 
                new Object[] {session.getId(), message});
        return "Server received [" + message + "]";
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Close connection for client: {0}", 
                session.getId());
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
    }
}

I use Tomcat 7.0.47, I check link: ws://localhost/Tests/chat. Do I need register this websocket or add some things in web.xml? Any idea why is not working for me?

like image 587
Nyger Avatar asked Nov 20 '13 09:11

Nyger


People also ask

Why WebSocket is not working?

Confirm that you're using a supported browser. If not, try using one of those and then check that WebSocket is working (see above). Proxy servers and firewalls. Check if you have a proxy server or firewall that blocks WebSocket access (you might need your system administrator's help).


1 Answers

I had the same problem trying to use WebSocket API on Tomcat 7.0.47. The error message being displayed client side wasn't any help at all and my server side endpoint was never being created.

After much wasted time I found it was due to way I had set the dependency for javax.websocket-api. I'm using Maven which has the default scope as compile which causes problems as Tomcat has the websocket-api.jar in its lib folder. Setting the dependency to provided solved it.

    <dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.0</version>
      <scope>provided</scope>
    </dependency>

Hope this helps

It's also worth noting that if running behind Apache you will need mod_proxy_wstunnel and if using IIS you will need version 8.0 as anything prior does not support websockets.

like image 163
samael Avatar answered Oct 13 '22 11:10

samael