packagecom.demo.util;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.io.OutputStreamWriter;importjava.net.Socket;importjava.util.HashMap;importjava.util.Map;importcom.alibaba.fastjson.JSON;public classSocketClient {public static voidmain(String[] args) {
InputStreamReader isr;
BufferedReader br;
OutputStreamWriter osw;
BufferedWriter rw;try{
Socket socket= new Socket("IP","端口号");
Map bodyMap= newHashMap();
Map headMap= newHashMap();
headMap.put("报文头", "报文头");
bodyMap.put("报文体", "报文体");
Map sendMap= newHashMap();
sendMap.put("head", headMap);
sendMap.put("body", bodyMap);
ByteArrayOutputStream baos= newByteArrayOutputStream();
String json=JSON.toJSONString(sendMap);
System.out.println("send message:" +json);byte[] content = json.getBytes("UTF-8");
String tmp= ("00000000" +String.valueOf(content.length));
String length= tmp.substring(tmp.length() - 8);
baos.write(length.getBytes());
baos.write(content);try{
writeStream(socket.getOutputStream(), baos.toByteArray());
Object result=readStream(socket.getInputStream());
System.out.println(result);
}catch(Exception e)
{
}finally{if (socket != null) {try{
socket.close();
}catch(IOException e) {
socket= null;
System.out.println("客户端 finally 异常:" +e.getMessage());
}
}
}
}catch(Exception e) {//TODO: handle exception
}
}protected static void writeStream(OutputStream out, byte[] sndBuffer) throwsIOException
{
out.write(sndBuffer);
out.flush();
}protected static Object readStream(InputStream input) throwsException {//TODO Auto-generated method stub
int headLength = 8;byte[] headBuffer = new byte[headLength];for (int offset = 0; offset
}
offset+=length;
}int totalLength = Integer.parseInt(new String(headBuffer, "UTF-8"));byte[] resultBuffer = new byte[totalLength];int offset = 0;while (offset = 0) {
offset+=realLength;
}else{
System.err.println("the length of packet should be :" + totalLength + " but encounter eof at offset:" +offset);throw new RuntimeException("invalid_packet_data");
}
}
String recvStr= new String(resultBuffer, "UTF-8");
System.out.println(recvStr);returnrecvStr.getBytes();
}
}