如何使用websockets正确地将客户端连接到服务器?

时间:2016-02-01 13:14:28

标签: java websocket

这是客户端

public class WidgetView extends Region {
    private WebView webView;
    private WebEngine webEngine;
    private ClientService service = new ClientService();
    public WidgetView() {
        setPrefSize(1000, 600);
        service.start();
        webView = new WebView();
        webView.setContextMenuEnabled(false);
        webEngine = webView.getEngine();
        webEngine.setOnAlert(event -> {
            System.out.println(event.getData().toString()); 
            sendToServer(event.getData().toString());
            //do something...

        });
        URL url = getClass().getResource("/ru/parus/imctax/web/index.html");
        webEngine.load(url.toExternalForm());
        getChildren().add(webView);
    }
    private void sendToServer(String json) {
        service.sendJson(json);
        System.out.println("Данные были отправлены!");
    }
    class ClientService extends Service<Session> {
        private Session session;
        @Override
        protected Task<Session> createTask() {
            Task<Session> task = new Task<Session>() {
                @Override
                protected Session call() throws Exception {
                    ClientManager client = ClientManager.createClient();
                    ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create().build();
                    URI uri = new URI("imc://localhost:8080/imc");
                    session = client.connectToServer(new ClientEndpoint(), endpointConfig, uri);
                    return session;
                }
            };
            return task;
        }
        void sendJson(String json) {
            //---------
            if (session == null) {
                System.out.println("Session is null ((");
                //This message printed on console
            }//---------
            if (session != null) {
                try {
                    System.out.println("Объект отправлен");
                    session.getBasicRemote().sendText(json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        void closeSession() {
            if (session != null) {
                try {
                    session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

ClientEndpoint

public class ClientEndpoint extends Endpoint {
    public ClientEndpoint() {
    }
    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String s) {
                System.out.println("Called method 'onMessage'. Parameter: "+s);
            }
        });
    }
}

服务器端

public class ServerMain {
    public static void main(String[] args) {
        Server server = new Server("localhost", 8080, "/imc", PurchaseServerEndpoint.class);
        try {
            server.start();
        } catch (DeploymentException e) {
            e.printStackTrace();
            server.stop();
        }
    }
}

//Another class in Server side
@ServerEndpoint("/imc")
public class PurchaseServerEndpoint {
    @OnOpen
    public void open(Session session) {
        System.out.println("Session ["+session+"] is open!");
    }
    @OnClose
    public void close(Session session) {
        System.out.println("Session ["+session+"] is closed!");
    }
    @OnMessage
    public void receiveJson(String message, Session session) {
        System.out.println("I'm receive json: " + message);
    }
}

我启动ServerApplication,然后启动ClientApp(带WebView的FxApp)。 数据未传递,因为会话为空。 也许这条线不正确?

session = client.connectToServer(new ClientEndpoint(), endpointConfig, uri);

如何使其正确?

1 个答案:

答案 0 :(得分:0)

URI uri = new URI("imc://localhost:8080/imc");

也许它应该是这样的:

URI uri = new URI("ws://localhost:8080/imc");

如果将服务器部署到某个应用程序服务器而不是在上下文路径中显示附加项 - 应用程序名称。例如,ws://localhost:8080/application_name/imc

相关问题