【问题标题】:can't get echo response from ws://echo.websocket.org in my websocket client在我的 websocket 客户端中无法从 ws://echo.websocket.org 获得回声响应
【发布时间】:2018-08-01 20:35:19
【问题描述】:

我正在尝试使用 javax websocket 库在 java 中实现一个简单的 websocket 客户端,这是我的代码:

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

import javax.websocket.*;

@ClientEndpoint
public class Client {

    Session session;

    private final static String url = "ws://echo.websocket.org";

    public static void main(String[] args) throws Exception, IOException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        System.out.println("connecting...");
        container.connectToServer(Client.class,
                URI.create(url));
    }


    @OnMessage
    public void newMessage(String message, Session session) {
        System.out.println(message);
    }
    @OnOpen
    public void newConnection(Session session) throws IOException {
        this.session = session;
        System.out.println("The connection has been started");
        session.getBasicRemote().sendText("hello");

    }
    @OnClose
    public void disconnection() {
        System.out.println("The connection has been ended");
    }
}

正如您在@OnOpen 注释中看到的,我尝试发送“Hello”字符串消息,而在@OnMessage 上我只想在控制台中打印消息。

我可以毫无错误地运行代码,但我只是得到了“正在连接...”打印,所以任何人都可以解释代码有什么问题吗?

注意:我将使用 javax.websocket 所需的 org.glassfish.tyrus 库也添加到了引用的库中

我是 Java 新手,很抱歉这个愚蠢的问题

【问题讨论】:

    标签: java websocket


    【解决方案1】:

    您的程序在调用container.connectToServer(...) 后立即退出,因此您的newConnection(...)newMessage(...) 函数永远没有机会运行。在调用container.connectToServer(...) 之后,您需要保持程序运行。例如,您可以通过在 container.connectToServer(...) 行之后添加以下代码来执行此操作,这将导致程序等待按下 ENTER 键:

            System.out.println("Press ENTER key to exit.");
            System.in.read();
    

    进行该更改后,您的程序在我的计算机上正常运行并显示“连接已启动”和“你好”消息。

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 2016-07-26
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多