package com.dcfs.esb.server.tcp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.text.DecimalFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dcfs.esb.pack.standardxml.PackUtil;
import com.dcfs.esb.server.global.DataUtils;
/**
* 数据处理类
* @author libin
*
*/
public class TCPService implements Runnable{
private static Log log = LogFactory.getLog(TCPService.class);
private Socket socket = null;
private String encoding = "UTF-8";
private int len=6;
public TCPService(Socket socket){
this.socket = socket;
}
public void run() {
byte[] respData = null;
InputStream is = null;
OutputStream os = null;
try{
is = new BufferedInputStream(socket.getInputStream());
byte[] headByte = readLenContent(is, len);
int length = Integer.parseInt(new String(headByte,encoding));
if(log.isDebugEnabled())
log.debug("请求数据长度为[" + length + "]");
byte[] reqByte = readLenContent(is, length);
if(log.isDebugEnabled()){
log.debug("请求数据为[" + new String(reqByte,encoding) + "]");
}
respData = getData("F:/testdata/5106.dat");
os = new BufferedOutputStream(socket.getOutputStream());
os.write(respData);
os.flush();
if(log.isDebugEnabled())
log.debug("resp[" + new String(respData,encoding) + "]");
}catch(Exception e){
if (log.isErrorEnabled()) {
log.error("服务器处理异常", e);
}
try {
respData = ("200018092209服务器处理异常").getBytes(encoding);
os.write(respData);
os.flush();
} catch (Exception e1) {
log.error("服务器处理异常", e);
}
}finally{
this.closeConnect(socket, os, is);
}
}
/**
* 从输入流读取指定长度数据
* @param is
* @param length
* @return
* @throws IOException
*/
private byte[] readLenContent(InputStream is, int length) throws IOException {
int count = 0;
int offset = 0;
byte[] retData = new byte[length];
while ((count = is.read(retData, offset, length - offset)) != -1) {
offset += count;
if (offset == length)break;
}
return retData;
}
/**
* 关闭连接
* @param socket
* @param os
* @param is
*/
private void closeConnect(Socket socket, OutputStream os,InputStream is) {
if(is != null){
try {
is.close();
} catch (IOException e) {
log.error(e);
}
is = null;
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error(e);
}
os=null;
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error(e);
}
socket = null;
}
}
/**
* 读取文件
*/
private static byte[] getData(String path) {
byte[] reqData = null;
try{
File file = new File(path);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int len = (int)file.length();
reqData = new byte[len];
bis.read(reqData);
} catch(Exception e){
System.out.println("获取数据出错"+e);
}
return reqData;
}
}