websocket 客户端短链接

最近对接一个项目,对方服务端居然使用webscoket服务,由于本地架构问题,需要使用短链接,因此写了一个短链接的websocket客户端。

依赖

<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.5.2</version>
 </dependency>

使用Java-Websocket 编写客户端,本身为异步,要改成类似http通讯的同步通讯,即链接、发送消息、等待接受消息、关闭链接 顺序执行,同时要控制链接超时时长,等待接收时长。使用java的Condition和ReentrantLock实现。

代码

package com.test;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * websocket 短链接
 */
public class WsShortClient {

    /**
     *  默认链接超时时间
     */
    public static final long CONN_TIMEOUT_DEFAULT = 10;

    /**
     * 默认发送超时时间
     */
    public static final long SEND_TIMEOUT_DEFAULT = 30;

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    /**
     * 访问地址
     */
    private String url;

    /**
     * 链接超时时长
     */
    private long connTimeOut;

    /**
     * 发送消息超时时长
     */
    private long sendTimeOut;

    public WsShortClient(String url){
        this.url = url;
        this.connTimeOut = CONN_TIMEOUT_DEFAULT;
        this.sendTimeOut = SEND_TIMEOUT_DEFAULT;
    }


    /**
     * 消息发送
     * @param msg
     * @return
     * @throws URISyntaxException
     * @throws InterruptedException
     */
    public String sendMessage(String msg) throws URISyntaxException, InterruptedException {
        final String[] response = {""};
        URI uri = new URI(this.url);
        WebSocketClient webSocketClient = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                lock.lock();
                try{
                    System.out.println(Thread.currentThread().getName() + ":websoket client 链接成功");
                    condition.signal();
                }finally {
                    lock.unlock();
                }
            }

            @Override
            public void onMessage(String message) {
                lock.lock();
                try {
                    response[0] = message;
                    System.out.println(Thread.currentThread().getName() + ":websoket client 收到消息:" + message);
                    condition.signal();
                }finally {
                    lock.unlock();
                }
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                System.out.println(Thread.currentThread().getName() + ":websoket client 链接关闭");
            }

            @Override
            public void onError(Exception e) {
                System.out.println(Thread.currentThread().getName() + ":websoket client 发生错误");
                e.printStackTrace();
            }
        };
        lock.lock();
        try {
            webSocketClient.connect();
            if (!condition.await(this.connTimeOut, TimeUnit.SECONDS)){
                System.out.println("链接超时");
            }
        }finally {
            lock.unlock();
        }
        lock.lock();
        try {
            webSocketClient.send(msg);
            if (!condition.await(this.sendTimeOut,TimeUnit.SECONDS)){
                System.out.println("发送消息等待接收超时");
            }
        }finally {
            lock.unlock();
        }
        webSocketClient.close();
        return response[0];
    }



    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public long getConnTimeOut() {
        return connTimeOut;
    }

    public void setConnTimeOut(long connTimeOut) {
        this.connTimeOut = connTimeOut;
    }

    public long getSendTimeOut() {
        return sendTimeOut;
    }

    public void setSendTimeOut(long sendTimeOut) {
        this.sendTimeOut = sendTimeOut;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值