0
点赞
收藏
分享

微信扫一扫

Java Socket 进行tcp请求和接收消息

夏天的枫_ 2022-04-21 阅读 45
public static String send(String cmdInfor) {
        StringBuilder sb = new StringBuilder();
        Socket clientSocket = null;
        OutputStream os = null;
        InputStream is = null;
        try {
            //要连接的服务端IP地址
            String host = "127.0.0.1";
            //要连接的服务端对应的监听端口
            int port = 10101;
            //将十六进制的字符串转换成字节数组
            byte[] cmdInfor2 = hexStrToBinaryStr(cmdInfor);

            //1.建立客户端socket连接,指定服务器位置及端口
            clientSocket = new Socket(host, port);
            clientSocket.setSoTimeout(1000*60);//一分钟超时

            //2.得到socket读写流
            os = clientSocket.getOutputStream();
            //输入流
            is = clientSocket.getInputStream();

            //3.利用流按照一定的操作,对socket进行读写操作
            os.write(cmdInfor2);
            os.flush();
            clientSocket.shutdownOutput();

            //接收服务器的响应-----------
            byte[] buf = new byte[1024];
            //接收收到的数据
            while (is.read(buf) != -1) {
                //将字节数组转换成十六进制的字符串
               sb.append(BinaryToHexString(buf));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(clientSocket != null) {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

举报

相关推荐

0 条评论