private int contentMsgBufferSize = 10000000;
private InetSocketAddress socketAddress;
private SocketChannel sckChannel;
private ByteBuffer buffMsgContent = ByteBuffer.allocate(contentMsgBufferSize);
private boolean isOpened = false;
private boolean isContinueOpenAfterUse = true;
private long waitReadTime = 5000;
private String serverIP="127.0.0.1";
private int port=8986;
private String communicatorName;
private static Object lockObj = new Object();
/**
* 打开TCP/IP通信口*/
public boolean open() {
//根据 IP地址/主机名和端口号创建套接字地址
socketAddress = new InetSocketAddress(serverIP, port);
try {
//打开套接字通道
sckChannel = SocketChannel.open();
//连接此通道的套接字
sckChannel.connect(socketAddress);
//调整此通道的为非阻塞模式
sckChannel.configureBlocking(false);
//完成套接字通道的连接过程
isOpened = true;
} catch (IOException e) {
logger.error("can't connect " + serverIP + ":" + port + "," + e.getMessage());
}
return isOpened;
}
/**
* 读写数据
*/
public byte[] writeAndReadBuffer(byte[] command, boolean isResponsable) throws IOException {
byte[] responseBuff = null;
synchronized (lockObj) {
writeBuffer(command);
if (isResponsable) {
try {
Thread.sleep(waitReadTime);
} catch (InterruptedException e) {
logger.error("TcpClientCommunicator writerAndReadBuffer error,InterruptedException:"
+ e.getMessage());
}
responseBuff = readBuffer();
}
return responseBuff;
}
}
/**
* 关闭通信口
*/
public void close() {
try {
//关闭此通道
sckChannel.close();
isOpened = false;
} catch (IOException e) {
logger.error(e.getMessage());
}
}