Socket接口请求方法详解
package com.engine.common.util;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketClient {
private static final String ENCODE_GBK = "GBK";
public final static String ENCODE_UTF_8 = "UTF-8";
public static final int CLIENT_HEAD_LEN = 8;
private Socket sc = null;
private String host;
private int port;
public SocketClient(String host, int port) {
this.host = host;
this.port = port;
}
public String sendData(String sendMsg) throws Exception {
String retStr = "";
InputStream is = null;
OutputStream os = null;
BufferedInputStream bis = null;
try {
sc = new Socket(host,port);
sc.setSoTimeout(300000);
is = sc.getInputStream();
os = sc.getOutputStream();
os.write((sendMsg).getBytes(ENCODE_GBK));
bis = new BufferedInputStream(is);
retStr = getReportData(bis);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("连接Socket服务器出错,服务器ip:" + host + ", 端口port:" + port);
}finally{
if(is != null) {
is.close();
}
if(os !=null ) {
os.close();
}
if(bis !=null ) {
bis.close();
}
}
return retStr;
}
private String getReportData(BufferedInputStream in) throws Exception
{
StringBuilder wenzi=new StringBuilder();
try{
byte[] headBytes = new byte[CLIENT_HEAD_LEN];
logger.info("CLIENT_HEAD_LEN---------------------------------------------{}",CLIENT_HEAD_LEN);
int temp = in.read(headBytes);
int dataLength = Integer.parseInt(new String(headBytes, ENCODE_GBK));
logger.info("dataLength---------------------------------------------{}",dataLength);
if (temp < CLIENT_HEAD_LEN || dataLength < 1){
throw new Exception("报文头部信息校验失败:" + new String(headBytes, ENCODE_GBK));
}
byte[] b=new byte[1024];
int i;
while((i=in.read(b))>0){
wenzi.append(new String(b,0,i,"GBK"));
}
logger.info("q请求的报文:{}",wenzi);
}
catch (Exception e){
e.printStackTrace();
throw new RuntimeException("报文信息截取失败");
}
return String.valueOf(wenzi);
}
}