?? h2socket.java
字號:
package com.sxit.nmunicom.h2;
import java.io.*;
import java.net.*;
import org.apache.log4j.Logger;
/**
* 建立和網關的socket連接
*
* @author HuaFeng
* @version 1.0 (2005-3-31 22:52:58)
*/
public class H2Socket {
/**
* Logger for this class
*/
protected static Logger logger = Logger.getLogger(H2Socket.class);
/**
* H2主機地址
*/
private static final String HOST="130.10.8.32";
/**
* 監聽端口
*/
private static final int PORT=10012;
/**
* 建立起的socket端
*/
private Socket socket;
/**
* 輸出流
*/
private OutputStream os;
/**
* 輸入流
*/
private DataInputStream is;
/**
* 構造函數
*
* @param host
* H2主機地址
* @param port
* 監聽端口
*/
public H2Socket() throws H2Exception {
initialSock();
}
/**
* 得到輸入流
*
* @return DataInputStream
*/
public DataInputStream getInputStream() {
return this.is;
}
public OutputStream getOutputStream() {
return this.os;
}
/**
* 初始化socket連接,設定超時時間為5秒 <br>
* 使用cmpp協議各命令之前,必須調用此方法
*
* @throws CMPPException
* 封裝連接時拋出的UnknownHostException以及IOException
*/
private void initialSock() throws H2Exception {
try {
if (socket == null) {
socket = new Socket(HOST, PORT);
}
socket.setSoTimeout(30 * 1000);
// socket.setSoLinger(true,0);
os = socket.getOutputStream();
is = new DataInputStream(socket.getInputStream());
logger.info("成功建立起和H2的socket連接");
} catch (UnknownHostException e) {
logger.error("地址\"" + HOST + "\"未知" + e.toString());
throw new H2Exception("UnknownHostException:" + e.getMessage());
} catch (IOException e) {
logger.error("建立socket IO異常:" + e.toString());
throw new H2Exception("IOException:" + e.getMessage());
}
}
/**
* 關閉socket連接
*
* @throws CMPPException
* 封裝關閉連接時拋出的IOException
*/
public void closeSock() throws H2Exception {
try {
if (socket != null) {
socket.close();
if (os != null) os.close();
if (is != null) is.close();
}
socket = null;
os = null;
is = null;
logger.info("socket連接關閉成功");
} catch (IOException e) {
logger.error("socket關閉異常:" + e.toString());
throw new H2Exception("IOException:" + e.getMessage());
}
}
/**
* socket連接上讀取輸入流
*
* @return 輸入流的字節形式
* @throws IOException
*/
public byte[] read(H2Message message) throws H2Exception {
try {
byte[] _head = new byte[7];
int reads = -1;
// 應該這樣讀,先讀7個字節,其中前2個字節為版本號信息,后5位為數據包大小
reads = is.read(_head, 0, 7);
// 沒有讀到的話
if (reads == -1) {
throw new H2Exception("讀包頭時輸入流已空,沒有讀到數據!");
}
byte[] a0=new byte[2];
System.arraycopy(_head, 0, a0, 0, 2);
message.setA0(new String(a0));
byte[] headlen=new byte[5];
message.setA1(new String(headlen));
System.arraycopy(_head, 2, headlen, 0, 5);
int packetlen = Integer.parseInt(new String(headlen).trim());
logger.debug("包體長度:::" + packetlen);
byte[] packet = new byte[packetlen];
if (packetlen > 0) {
// 整個輸入流的字節形式
// 如果輸入流還有包體
// int size=is.read(packet,0,packetlen);
int size = is.read(packet);
logger.info("本次輸入流讀取完畢,預計長度=" + packetlen + ",實際長度:" + (size+7));
}
return packet;
} catch (IOException e) {
throw new H2Exception("讀包錯誤:" + e.getMessage());
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -