java websocket客户端代码

不废话直接上 我的java websocket源码,跑通了的

引用的jar包

        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.2</version>
        </dependency>

import okhttp3.*;
import okio.ByteString;

public class Client extends WebSocketListener {
   
    public static void main(String[] args) throws Exception {
        System.out.println("开始");
        // 构建鉴权url
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url("ws://ip:port/xx").build();
        client.newWebSocket(request, new Client());

        while (true){
            System.out.println("主线程休眠2s,保证进程不结束");
            Thread.sleep(2000);
        }
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        webSocket.send("hello");
    }
    @Override
    public void onMessage(WebSocket webSocket, String text) {
    	super.onMessage(webSocket, text);
        System.out.println("String text="+text);
//        if(true){//如果连接可以关闭了,就close
//            webSocket.close(1000,"");
//        }
    }
    @Override
    public void onMessage(WebSocket webSocket, ByteString text) {
    	super.onMessage(webSocket, text);
        System.out.println("ByteString text="+text);
    }
    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值