首页 > 解决方案 > 带有 glassfish 的 Java Websocket,在 Firefox 中出现错误 405

问题描述

我在java 7中创建一个websocket,使用glassfish作为服务器,我为客户端创建类和服务器端类,我添加@ServerEndpoint,我创建url并在javascript中调用websocket,但我得到了和 405 错误,我不知道原因,但在控制台中说那是因为 get 方法

我使用客户端的下一个代码

@ClientEndpoint
public class WSClient  {
    private static Object waitLock = new Object();

@OnMessage
    public void onMessage(String message) {
       System.out.println("Received msg: "+message);        
    }

 private static void  wait4TerminateSignal()
 {
  synchronized(waitLock)
  {try {
    waitLock.wait();
   } catch (InterruptedException e) {    
   }}}
    
    public static void main(String[] args) {
    WebSocketContainer container=null;//
         Session session=null;
      try{
       container = ContainerProvider.getWebSocketContainer(); 
    
    session=container.connectToServer(WSClient.class, URI.create("ws://localhost:8888/nsjp-web-pg/mensaje")); 
    
       wait4TerminateSignal();
      } catch (Exception e) {
       e.printStackTrace();
      }
      finally{
       if(session!=null){
        try {
     session.close();
        } catch (Exception e) {     
         e.printStackTrace();
        }
       }         
      } 
     }
}

and in the server side i have this code



@ServerEndpoint("/mensaje")

公共类 WebSocket 扩展 HttpServlet{

private static final long serialVersionUID = 1L;

@OnOpen
public void onOpen(Session session) {
    System.out.println("onOpen::" + session.getId());        
}
@OnClose
public void onClose(Session session) {
    System.out.println("onClose::" +  session.getId());
}

@OnMessage
public void onMessage(String message, Session session) {
    System.out.println("onMessage::From=" + session.getId() + " Message=" + message);
    
    try {
        session.getBasicRemote().sendText("Hello Client " + session.getId() + "!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@OnError
public void onError(Throwable t) {
    System.out.println("onError::" + t.getMessage());
}

}

最后是javascript中的调用

var websocket= new WebSocket("ws://localhost:8888/nsjp-web-pg/mensaje");

before i was getting and 404 error, but was by the url, i fix the error and now change to 405

标签: javascriptwebsocketjava-7glassfish-3java-websocket

解决方案


推荐阅读