[Java]利用OKHttp3作为客户端连接WebSocket服务器

2022-01-19 158点热度 0人点赞 0条评论

之前的文章,写了一个Java(SpringBoot)的WebSocket服务器端,详见:https://blog.terrynow.com/2022/01/11/java-springboot-implement-websocket-server-sample-codes-manage-sessions-send-messages-inject-services/

如果要使用Java作为客户端去连那个服务器端,要怎么做呢?

可以使用OKHttp来做,简单几行代码就搞定。

Maven pom.xml引入:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.2</version>
</dependency>

实现代码

import okhttp3.*;

public class Test1 extends WebSocketListener {
    public static void main(String[] args) {
        new Test1().test();
    }

    public void test() {
        String wsUrl = "http://192.168.1.81:9105/webSocket/1111";
        Request request = new Request.Builder().url(wsUrl).build();
        WebSocket webSocket = new OkHttpClient.Builder().build().newWebSocket(request, this);
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        System.out.println("websocket on open");
        super.onOpen(webSocket, response);
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        System.out.println("websocket on close");
        super.onClosed(webSocket, code, reason);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println("websocket received message: "+text);
        super.onMessage(webSocket, text);
    }
}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论