socket 异步双工
之前没接触过,最近遇到了,看了别人的代码才明白什么意思:发送一次交易数据完成后不用等待这次的响应的返回,另外起一个异步的接收线程处理对方响应的数据,这就是异步;发送和接受使用同一个socket连接对象,这就是双工。
下面直接上代码:
SocketUtil代码:
package asy.single;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import util.StrUtil;
public class SocketUtil {
private static String ip;
private static int port;
private static Socket socket;
private static int retryDelay;//socket连接失败后重试间隔
private static int retrySize;//socket连接失败后重试次数,如果小于0表示一直重试
private static String heartText;
private static ResourceBundle prop;
private static Thread heartBeat;
private static Thread recieve;
private static boolean running;
private static Map<String, String> defaultMap = new HashMap<String, String>(){
private static final long serialVersionUID = 3492949030265745295L;
{
this.put("retryDelay", "3000");
this.put("retrySize", "-1");
this.put("heartText", "心跳数据");
}
};
static {
init();
}
public static void init(){
prop = ResourceBundle.getBundle("asy/single/socket", Locale.getDefault());
ip = prop.getString("ip");
port = Integer.parseInt(prop.getString("port"));
retryDelay = StrUtil.string2T(prop.getString("retryDelay"), defaultMap.get("retryDelay"), Integer.class);
retrySize = StrUtil.string2T(prop.getString("retrySize"), defaultMap.get("retrySize"), Integer.class);
heartText = StrUtil.string2T(prop.getString("heartText"), defaultMap.get("heartText"), String.class);
//retryDelay = StrUtil.emptyDefaultInt(prop.getString("retryDelay"), defaultMap.get("retryDelay"));
//retrySize = StrUtil.emptyDefaultInt(prop.getString("retrySize"), defaultMap.get("retrySize"));
//heartText = StrUtil.emptyDefaultString(prop.getString("heartText"), defaultMap.get("heartText"));
}
public boolean startSocket() {
System.out.println("#####################################################连接socket start###################################################");
int size = retrySize;
int<