如何发送十六进制字节数组并通过Socket获得响应

时间:2017-11-20 07:14:05

标签: java arrays sockets hex

有人可以演示如何通过TCP连接从发送程序向Java中的接收程序发送字节数组。 这是一个来源

public class TCPClient
{
public static final String SERVER_IP ="********";
public static final int SERVER_PORT = 8022;
public static void main(String[] args) throws Exception
{
    System.out.println("Client Started..." +hostAvailabilityCheck());

    Socket socket = new Socket(SERVER_IP, SERVER_PORT);
    socket .setSoTimeout(10000);

    DataInputStream is = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    DataOutputStream os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    String sendapduString2 = "someapducommand";//get info

    byte[] sendapdu2 = hexStringToByteArray(sendapduString2);
    send(os, sendapdu2);
    System.out.println("Data sent to Server ; Message = " );

    try
    {
        while (true)
        {
            // Receive Server Response
            byte[] byteData = receive(is);
            String responseData = new String(byteData);
            System.out.println("Server Response = " + responseData.trim());
        }
    }
    catch (Exception e)
    {
        System.out.println("Exception: " + e.getMessage());
    }
}


public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}

public static boolean hostAvailabilityCheck() {
    try (Socket s = new Socket(SERVER_IP, SERVER_PORT)) {
        return true;
    } catch (IOException ex) {
    /* ignore */
    }
    return false;
}
/**
 * Method receives the Server Response
 */
public static byte[] receive(DataInputStream is) throws Exception
{
    try
    {
        byte[] inputData = new byte[1024];
        is.read(inputData);
        return inputData;
    }
    catch (Exception exception)
    {
        throw exception;
    }
}

/**
 * Method used to Send Request to Server
 */
public static void send(DataOutputStream os, byte[] byteData) throws Exception
{
    try
    {
        os.write(byteData);
        os.flush();
    }
    catch (Exception exception)
    {
        throw exception;
    }
}

} 如您所见,我编写了函数来转换十六进制字节数组中的字符串。 我想将我的字节数组发送到服务器,响应应该是十六进制字节数组。 这是我的结果

Exception: Read timed out

有人可以告诉我,我的来源有什么问题吗?

1 个答案:

答案 0 :(得分:0)

如异常所示,服务器没有写任何响应或处理输入流太慢而无法及时响应。