Server/Socket

来源:互联网 发布:带网络的pe系统 编辑:程序博客网 时间:2024/06/05 05:51
public static byte[] process(byte[] sendinfo) throws InterfaceException{
// socket对象
Socket socket = new Socket();

byte [] returnByte = null;

InputStream input =null;

OutputStream oupt =null;

InetSocketAddress address = new InetSocketAddress("",1);

try {
// 连接
socket.connect(address);

// 判断是否连接
if(!socket.isConnected()){
throw new InterfaceException("socket连接失败");
}
oupt = socket.getOutputStream();
// 发送内容
oupt.write(sendinfo);
// 释放
oupt.flush();
int a=0;
int i=0;
ArrayList<Object> byteArrayBuilder = new ArrayList<Object>();
// 获取返回结果
input = socket.getInputStream();
while (true){
if(i>2){
a = input.read();
if(a == -1){
break;
}else{
byteArrayBuilder.add(new Byte((byte)a));
}
i++;
}
returnByte = toByteArray(byteArrayBuilder);
}

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
input.close();
oupt.close();
} catch (IOException e) {
throw new InterfaceException(e.getMessage());
}

}

return returnByte;
}



public static byte[] toByteArray(ArrayList<Object> byteArrayBuilder){

ByteBuffer buffer = ByteBuffer.allocate(byteArrayBuilder.size());
for(int i=0;i<byteArrayBuilder.size();i++){
buffer.put(ConvertUtils.convert(byteArrayBuilder.get(i)));
}
return buffer.array();
}


public static byte[] convert(Object value) {
if (value == null) {
return null;
}
if (value instanceof Byte) {
return convert((Byte)value);
}
else if(value instanceof Short) {
return convert((Short)value);
}
else if(value instanceof Integer) {
return convert((Integer)value);
}
else if (value instanceof String) {
return convert((String)value);
}
else if (value instanceof  byte[]) {
return (byte[])value;
}
else {
throw new IllegalArgumentException();
}
}

public static byte[] convert(Byte value) {
        return new byte[]{value.byteValue()};
}

public static byte[] convert(Short value) {
        byte[] result = new byte[2];
        result[1] = (byte) (0xff & value);
        result[0] = (byte) ((0xff00 & value) >> 8);
        return result;
}


public static byte[] convert(Integer value) {
        byte[] result = new byte[4];
        result[3] = (byte) (0xff & value);
        result[2] = (byte) ((0xff00 & value) >> 8);
        result[1] = (byte) ((0xff0000 & value) >> 16);
        result[0] = (byte) ((0xff000000 & value) >> 24);
        return result;
}

public static byte[] convert(String value) {
try {
if (value != null) {
return value.getBytes(CHARSET_GBK);
}
else {
return new byte[0];
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}