java客户端发送socket消息到指定服务并接收响应

做个笔记

  /**
     * 发送socket到指定服务
     * 接收有6位报文头长度的响应,支持读取分包
     *
     * @param host IP
     * @param port 端口
     * @param msg  消息内容,自己加报文头长度哦
     * @return
     * @throws Exception
     */
    public static String send(String host, String port, String msg) throws Exception {
        System.out.println("socket发送,host=" + host + ",port=" + port + ",msg=" + msg);
        try (Socket socket = new Socket(host, Integer.parseInt(port));) {
            OutputStream os = socket.getOutputStream();
            os.write(msg.getBytes());
            System.out.println("=======已成功发送=======");
            InputStream is = socket.getInputStream();
            StringBuilder ret = new StringBuilder();
            //这里每次读的长度可以自己改
            byte[] bys = new byte[1024];
            int len = 0;
            //6代表长度头的长度
            byte[] headBytes = new byte[6];
            int headRead = is.read(headBytes);
            String head = new String(headBytes, 0, headRead, StandardCharsets.UTF_8);
            ret.append(head);
            System.out.println("head=" + head);
            int headLength = Integer.parseInt(head);
            int current = 0;
            while (true) {
                len = is.read(bys);
                current = current + len;
                if (len == 0) {
                    continue;
                }
                if (len == -1) {
                    break;
                }
                String str = new String(bys, 0, len, StandardCharsets.UTF_8);
                ret.append(str);
                if (current == headLength) {
                    break;
                }
            }
            //输出数据
            System.out.println("socket接收,host=" + host + ",port=" + port + ",msg=" + ret.toString());
            //释放资源
            socket.close();
            return ret.toString();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("发送失败");
        }
    }
posted @ 2023-04-27 16:51  DaenMax  阅读(471)  评论(0编辑  收藏  举报