当前位置:   article > 正文

JAVA开启socket从流中读取2进制并转化为16进制_java serversocket 接收请求 二进制转十六进制

java serversocket 接收请求 二进制转十六进制
public class SocketReceiveUtil {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            String rtfNumber = getRtfNumber();
            System.out.println(rtfNumber);
        }
    }

    private static String getRtfNumber() {
        try {
            return getNumber();
        } catch (Exception e) {
            System.out.println("获取数据超时");
            return "";
        }
    }

    public static String getNumber() throws Exception {
        ServerSocket server = new ServerSocket(8888);
        try {
            Socket client = server.accept();
            client.setSoTimeout(1000);
            try {
                InputStream inputStream = client.getInputStream();
                byte[] bytes = new byte[1025];
                int readBytes = 0;
                int len = bytes.length;
                while (readBytes < len) {
                    int read = inputStream.read(bytes, readBytes, len - readBytes);
                    //判断是不是读到了数据流的末尾 ,防止出现死循环。
                    if (read == -1) break;
                    readBytes += read;
                }
                String resultNum = byteArrayToHexString(bytes);
                return StringUtils.isNotBlank(resultNum) ? resultNum : "";
            } finally {
                client.shutdownInput();
                client.close();
            }
        } finally {
            server.close();
        }
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));
        return resultSb.toString();
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/618025
推荐阅读
相关标签
  

闽ICP备14008679号