/**
String ip 服务器ip
int port, 服务器端口
byte[] data 发送的数据
*/
public static byte[] bySocketGetMassage(String ip, int port, byte[] data) throws Exception {
//客户端
//1、创建客户端Socket,指定服务器地址和端口
Socket socket = new Socket(ip, port);
// socket.setSoTimeout(30 * 1000);
//2、获取输出流,向服务器端发送信息
OutputStream os = socket.getOutputStream();//字节输出流
os.write(data);
os.flush();
//3、获取输入流,并读取服务器端的响应信息
InputStream is = socket.getInputStream();
//注意new byte[8] 指的是 整个报文的最前面8位 为长度位 最先读取长度位;再按照长度为读取剩余的数据,所以这里的8请根据 实际的返回报文 数据 的约定(比如前6位,那么这里为 new byte[6])
byte[] bytes = new byte[8];
if (8 != is.read(bytes))
throw new Exception("报文头读取异常");
int len = Integer.parseInt(new String(bytes));
System.out.println("读取报文长度:" + len);
byte[] body = new byte[len];
if (len != is.read(body))
throw new Exception("报文长度读取不足");
//4、关闭资源
is.close();
os.close();
socket.close();
return groupBytes(bytes, body);
}
public static byte[] groupBytes(byte[]... chars) {
int size = 0;
for (byte[] cs : chars)
size += cs.length;
byte[] result = new byte[size];
int index = 0;
for (byte[] cs : chars) {
System.arraycopy(cs, 0, result, index, cs.length);
index += cs.length;
}
return result;
}