在OSGi容器中使用tyrus的Java websocket客户端

时间:2015-07-22 16:54:28

标签: java websocket osgi tyrus

正如问题标题中所解释的那样,我正在尝试将WebSocket客户端创建到Java(JAR)应用程序中,该应用程序稍后将部署到OSGi容器中(如果有人知道此框架,则为KURA)。

我正在使用Tyrus作为javax.websocket实现。请注意,我在我的应用程序中导入的唯一库是: tyrus-standalone-client-1.11.jar

按照我的代码:

Client.java

import java.io.IOException;
import java.net.URI;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

import org.glassfish.tyrus.client.ClientManager;

public class Client {
private Session session;

public void connect() {
    try {
        final ClientEndpointConfig configuration = ClientEndpointConfig.Builder.create().build();
        ClientManager client = ClientManager.createClient();
        client.connectToServer(
            new Endpoint() {
                @Override
                public void onOpen(Session session,EndpointConfig config) {
                    Client.this.session = session;
                    Client.this.session.addMessageHandler(new MessageHandler.Whole() {
                        @Override
                        public void onMessage(Object message) {
                            System.out.println("Received message: "+message);
                        }
                    });
                }
            },
            configuration, new URI("ws://echo.websocket.org"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

然后在 main.java

    Client client = new Client();
    client.connect();
    try {
        client.sendMessage("hello world");
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

当我尝试运行此代码时,我总是抓住同样该死的例外:

java.lang.ClassCastException: org.glassfish.tyrus.container.grizzly.client.GrizzlyClientContainer cannot be cast to org.glassfish.tyrus.spi.ClientContainer

我试图修改这条线:

ClientManager client = ClientManager.createClient();

ClientManager client = ClientManager.createClient("org.glassfish.tyrus.client.ClientManager");

以下结果是:

java.lang.RuntimeException: javax.websocket.DeploymentException: Class org.glassfish.tyrus.client.ClientManager couldn't be instantiated.

我做错了什么?

提前感谢所有人。

0 个答案:

没有答案