1.先建立Socket對象,並鏈接服務器的IP和端口號
2.鏈接創建後,經過map格式輸出流向服務器端發送請求報文
3.經過輸入流獲取服務器響應的報文
4.關閉相關資源java
代碼以下:json
package com.demo.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; public class SocketClient { public static void main(String[] args) { InputStreamReader isr; BufferedReader br; OutputStreamWriter osw; BufferedWriter rw; try { Socket socket = new Socket("IP","端口號"); Map bodyMap = new HashMap(); Map headMap = new HashMap(); headMap.put("報文頭", "報文頭"); bodyMap.put("報文體", "報文體"); Map sendMap = new HashMap(); sendMap.put("head", headMap); sendMap.put("body", bodyMap); ByteArrayOutputStream baos = new ByteArrayOutputStream(); 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) throws IOException { out.write(sndBuffer); out.flush(); } protected static Object readStream(InputStream input) throws Exception { // TODO Auto-generated method stub int headLength = 8; byte[] headBuffer = new byte[headLength]; for (int offset = 0; offset < headLength;) { int length = input.read(headBuffer, offset, headLength - offset); if (length < 0) { throw new RuntimeException("invalid_packet_head"); } offset += length; } int totalLength = Integer.parseInt(new String(headBuffer, "UTF-8")); byte[] resultBuffer = new byte[totalLength]; int offset = 0; while (offset < totalLength) { int realLength = input.read(resultBuffer, offset, totalLength - offset); if (realLength >= 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); return recvStr.getBytes(); } }