如何在jetty容器中设置JSR356 websockets

时间:2014-10-30 16:40:29

标签: java websocket jetty jsr356

我看到很多关于如何使用某种嵌入式Web服务器设置JSR356 websockets的教程。

但我想在部署到独立码头安装的现有WAR上添加一些websockets,jetty jetty-9.2.3.v20140905,我可以找到很少的信息。我无法弄清楚阻止它工作的原因。据我了解,带注释的服务器端点应由jetty自动处理。

ServerEndpoint:

    @ServerEndpoint(value = "/myendpoint")
public class MyServerEndpoint {     
    private Logger logger = Logger.getLogger(this.getClass().getName());     

    @OnOpen 
    public void onOpen(Session s) {
        logger.info("Server Connected ... " + s.getId());
        s.getAsyncRemote().sendText("You are connected to the websocket server");   
    }        

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

        // Sent the message back to all connected users             
        logger.info("Server Session " + session + " Received string message " + message);

        for(Session s: session.getOpenSessions()) {     
            if (s.isOpen()) { 
                s.getAsyncRemote().sendText(message + " server response");
            }       
        }   
    }        

    @OnClose    
    public void onClose(Session session, CloseReason reason) {
        logger.info("Server Session " + session + " closed for reason " + reason);
    }   
}

ClientEndpoint:

    @ClientEndpoint
public class MyClientEndpoint {     
    private Logger logger = Logger.getLogger(this.getClass().getName());     

    @OnOpen 
    public void onOpen(Session s) {
        logger.info("Client Connected ... " + s.getId());
        s.getAsyncRemote().sendText("hello from the client!");  
    }        

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

        logger.info("Client Session " + session + " Received string message " + message);       

    }        

    @OnClose    
    public void onClose(Session session, CloseReason reason) {
        logger.info("Client Session " + session + " closed for reason " + reason);
    }   
}

以下是将客户端连接到服务器的代码(在一些现有方法中运行)

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    String uri = "ws://localhost:8080/myWar/myendpoint"; 
    container.connectToServer(MyClientEndpoint.class, URI.create(uri));

然而,启动jetty会在connectToServer线路上出现错误

2014-10-30 12:26:58.658:WARN:oeja.ServletContainerInitializersStarter:main: 
org.eclipse.jetty.websocket.api.InvalidWebSocketException: Unable to instantiate websocket: class java.lang.Class
at   org.eclipse.jetty.websocket.jsr356.ClientContainer.newClientEndpointInstance(ClientContainer.java:311)
    at org.eclipse.jetty.websocket.jsr356.ClientContainer.connectToServer(ClientContainer.java:172)

我所能想到的是URI不正确。如果jetty在8080上运行而我的.war命名为myWar,而我的终点名为myendpoint ...那不是正确的URI吗?

是否需要执行一些额外的步骤来“激活”服务器端点以侦听连接?我一定错过了一些明显的东西。

2 个答案:

答案 0 :(得分:1)

奇怪的是,您的错误消息。

org.eclipse.jetty.websocket.api.InvalidWebSocketException: 
  Unable to instantiate websocket: class java.lang.Class

表示websocket实现被传递给原始的java.lang.Class来实例化。 那不行。

这也意味着没有尝试连接,因为WebSocket类本身非常糟糕,连接是不可能的。

这是一个显示其用途的简短(有效且有效)示例。

package jetty.jsr356;

import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CountDownLatch;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class TestClientAnnotatedClass
{
    private static CountDownLatch closeLatch = new CountDownLatch(1);

    @OnOpen
    public void onOpen(Session session)
    {
        System.out.println("@OnOpen - " + session);
        try
        {
            session.getBasicRemote().sendText("Rock it with Java WebSocket");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(Session session, String msg)
    {
        System.out.println("@OnMessage - ["+msg+"]");
        try
        {
            session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE,"Thanks"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(CloseReason close)
    {
        System.out.println("@OnClose - " + close);
        closeLatch.countDown();
    }

    public static void main(String[] args)
    {
        try
        {
            WebSocketContainer ws = ContainerProvider.getWebSocketContainer();

            ws.connectToServer(TestClientAnnotatedClass.class,new URI("ws://echo.websocket.org/?encoding=text"));
            closeLatch.await();
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    }
}

您会看到与此类似的输出

2014-10-30 11:34:19.197:INFO::main: Logging initialized @71ms
@OnOpen - WebSocketSession[websocket=JsrAnnotatedEventDriver[websocket=jetty.jsr356.TestClientAnnotatedClass@5cca5f2c],behavior=CLIENT,connection=WebSocketClientConnection@6a2e714b{IDLE}{f=Flusher[queueSize=0,aggregateSize=0,failure=null],g=Generator[CLIENT,validating],p=Parser@55465b1f[ExtensionStack,s=START,c=0,len=0,f=null,p=WebSocketPolicy@7e087bf5[behavior=CLIENT,maxTextMessageSize=65536,maxTextMessageBufferSize=32768,maxBinaryMessageSize=65536,maxBinaryMessageBufferSize=32768,asyncWriteTimeout=60000,idleTimeout=300000,inputBufferSize=4096]]},remote=WebSocketRemoteEndpoint@5f025277[batching=true],incoming=JsrAnnotatedEventDriver[websocket=jetty.jsr356.TestClientAnnotatedClass@5cca5f2c],outgoing=ExtensionStack[queueSize=0,extensions=[],incoming=org.eclipse.jetty.websocket.jsr356.JsrSession,outgoing=org.eclipse.jetty.websocket.client.io.WebSocketClientConnection]]
@OnMessage - [Rock it with Java WebSocket]
@OnClose - CloseReason[1000,Thanks]

答案 1 :(得分:0)

Jetty使用反射创建带注释的客户端端点的实例(请参阅/jetty/websocket/jsr356/ClientContainer#newClientEndpointInstance()),但 Java无法以这种方式实例化非静态内部类。实际原因异常类似于java.lang.NoSuchMethodException: <pkg>.OuterClass$InnerClass.<init>(),但它被吞噬了。

解决方案:带注释的端点类不应嵌套或嵌套静态(内部)类。