Java经过Socket实现TCP/IP协议的通讯(客户端)

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(); } }
相关文章
相关标签/搜索