All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zlyx.easynetty.client.BlockNettyClient Maven / Gradle / Ivy

package com.zlyx.easynetty.client;

import java.util.ArrayList;
import java.util.List;

import com.zlyx.easycore.utils.ByteUtils;
import com.zlyx.easynetty.client.AbstractNettyClient;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;

/**
 * @Auth 赵光
 * @Desc Netty阻塞式->长连接->客户端
 * @Date 2019年4月28日
 */
@Sharable
public class BlockNettyClient extends AbstractNettyClient{
	
	private int waittime;
	
	private List list = new ArrayList<>();
	
	private String data;
	
	private String response;
	
    /**
     * 是否等待响应结果(0:休眠或响应已返回;1:等待响应)
     */
	private int isWait;
	
	public BlockNettyClient(String key, String host, int port, String data) throws Exception {
		this(key, host, port, data, 300);
	}
	
	public BlockNettyClient(String key, String host, int port, String data, int waittime) throws Exception {
		super(key, host, port);
		this.waittime = waittime;
		this.data = data;
	}

	@Override
	public void doOnConnection(ChannelHandlerContext ctx) throws Exception {
		this.isWait = 1;
		this.write(data);
	}

	@Override
	public String doService(Channel channel, byte[] msg) throws Exception {
		this.response = ByteUtils.bytesToHexString(msg);
		this.isWait = 0;
		return null;
	}

	/**
	 * 等待响应(阻塞式)
	 * @param millis
	 * @return 
	 * @throws Exception 
	 */
	public String getResponse() throws Exception {
		do{
		   Thread.sleep(waittime);
		}while(this.isWait == 1);
		return response;
	}

	/**
	 * 发送数据
	 * @param data
	 * @return
	 * @throws Exception 
	 */
	public void doSend(String data) throws Exception {	
		this.list.add(data);
	}
	
	@Override
	public void run() {
		try {
			super.run();
			while(true) {
				if(this.list.size() > 0){
					this.data = this.list.get(0);
					this.list.remove(0);
					this.write(data);
				}else {
                    Thread.sleep(waittime);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy