Socket -tcp/ip

来源:互联网 发布:地区数据库 编辑:程序博客网 时间:2024/06/04 06:42


public class SocketUtil {
private final LogManager LOGGER=new LogManager("SocketUtil");
private final int CON_TIMEOUT = 1000*20; //连接超时时长
private String host;  //主机
private int port;     //端口

private Socket socket=null;
private InetSocketAddress isa = null; 
private DataInputStream dis=null;
private DataOutputStream dos=null;

private TimeoutThread timeoutThread = null;

private boolean timeout = false;



public void setHostPort(String host,int port){
close();
this.host = host;
this.port = port;
}

/**
* 发送请求,并返回请求结果
* @param message
*/
public synchronized String write(String message){
String result="网络异常!";
try {
byte buf[]=new byte[message.length()/2];//16进制发送
int offset=0;
LOGGER.debug("message:"+message);
for (int i=0;i<message.length()/2;i++) {    //把16进制字符串转换成byte数组
offset=i*2;
String contentStr = message.substring(offset,offset+2);
String intStr = String.valueOf(Integer.parseInt(contentStr,16));
buf[i]=(byte)(Integer.parseInt(intStr)&0xFF);  
}

if(socket==null){
create();
}

if(socket.isConnected()==false){
LOGGER.error("======= Recreate Socket =========");
close();
create();
}


LOGGER.error("======= send req date =========");
dos.write(buf);
dos.flush();
result = read();


   }catch(Exception e){
    e.printStackTrace();
    close();
   }
return result;
}


private String read(){
timeout = false;
int size =0;
String msg = null;


timeoutThread = new TimeoutThread();
timeoutThread.start();


while(timeout==false&&size==0){
try{
    size=dis.available();
    //LOGGER.debug("read size>>>>>>"+size+"timeout="+timeout);
    if(size>0){
    byte[] buffer = new byte[size];
       dis.read(buffer);
       msg=DataUtil.bytesToHexString(buffer).toUpperCase();
       LOGGER.debug("msg:"+msg);
    }
}catch(IOException ioe){
    LOGGER.debug("数据接收异常!!");
    break;
}
}
if(timeoutThread!=null){
timeoutThread.interrupt();
timeoutThread=null;
}


return msg;
}

/**
* 创建连接
* @return
*/
private String create(){
try{
//LOGGER.info("Connecting... host:"+host+",port:"+port);
socket = new Socket(); 

isa = new InetSocketAddress(host,port); 


socket.connect(isa,CON_TIMEOUT);
socket.setKeepAlive(true);

//获取Socket输入输出流进行读写操作
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());

LOGGER.debug("Connect address:"+socket.getRemoteSocketAddress().toString());
LOGGER.info("========= Connect is OK ========");
return "OK";
}catch(Exception e){
LOGGER.error("========= Connect is failed!=========");
e.printStackTrace();
close();
return "网络异常!";
}
}

/**
* 关闭连接
*/
private void close(){
try{
//关闭写入流
if(dis!=null){
dis.close();
dis=null;
}

//关闭写出流
if(dos!=null){
dos.close();
dos=null;
}

//关闭socket
if(socket!=null){
socket.close();
socket=null;
}
}catch(Exception e){
e.printStackTrace();
}
}


/**
* 超时处理线程
* @author yxj
*
*/
public class TimeoutThread extends Thread{
public void run() {
int delayms = 20*1000;
while(delayms>0){
try{
delayms = delayms-100;
sleep(100);
}catch(Exception e){
e.printStackTrace();
}
}
if(delayms<=0){
timeout=true;
}
}
}

}

/*

应用 例子

new Thread(){
@Override
public void run() {
SocketUtil socket = IparkApplication.getSocket();
if(socket==null){
socket= new SocketUtil();
socket.setHostPort(IparkApplication.getHostPort().getHost(), IparkApplication.getHostPort().getPort());
IparkApplication.setSocket(socket);
}
String rspStr = socket.write(reqMsg);//写书数据  里面 包含了Soclet的链接 
if(rspStr==null||rspStr.equals("网络异常!")){
handler.sendEmptyMessage(NET_ERR);
}else{
//解析数据
resulteBerthPo = new GetBerthsResultPo();
CommonDecoderr cDecoder = new CommonDecoderr();
cDecoder.decode(rspStr);
String subContent=cDecoder.getSubPackege();
LOGGER.debug("subCotent:"+subContent);
if(subContent!=null){
GetBerthsDecoder.decode(resulteBerthPo, subContent);
LOGGER.debug("berths---"+resulteBerthPo.toString());
handler.sendEmptyMessage(GET_BERTH_SUCESS);
}else{
handler.sendEmptyMessage(GET_BERTH_FAIL);
}


}
}
}.start();


*/



0 0
原创粉丝点击