首页 > 编程语言 > 详细

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

时间:2020-01-13 17:39:59      阅读:108      评论:0      收藏:0      [点我收藏+]

1.先创建Socket对象,并连接服务器的IP和端口号
2.连接建立后,通过map格式输出流向服务器端发送请求报文
3.通过输入流获取服务器响应的报文
4.关闭相关资源

 

代码如下:

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();
    }
}

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

原文:https://www.cnblogs.com/shulanteacher/p/12188106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!