Java 如何处理和解码来自TCP服务器的传入字节

Java 如何处理和解码来自TCP服务器的传入字节,java,tcp,byte,decoding,Java,Tcp,Byte,Decoding,我目前正在开发一个Java控制台应用程序。它通过命令提示符运行,连接到用python编码的服务器应用程序,并通过TCP与该服务器通信。我的应用程序将“ISND”字符串发送到它接受的服务器,作为回报,服务器发送三个图像。发送图像的格式为 其中实际上不包括“”。“ISND”使用ascii编码为字节。Size是从int转换为字节的图像大小,无论图像大小如何,它始终由3个字节组成。对于每个单独的图像,将发送此格式的消息 我一直在使用BufferedReader读取服务器响应,但此时,我不知道如何实际处

我目前正在开发一个Java控制台应用程序。它通过命令提示符运行,连接到用python编码的服务器应用程序,并通过TCP与该服务器通信。我的应用程序将“ISND”字符串发送到它接受的服务器,作为回报,服务器发送三个图像。发送图像的格式为

其中实际上不包括“”。“ISND”使用ascii编码为字节。Size是从int转换为字节的图像大小,无论图像大小如何,它始终由3个字节组成。对于每个单独的图像,将发送此格式的消息

我一直在使用BufferedReader读取服务器响应,但此时,我不知道如何实际处理此消息。我一直在寻找将传入消息分成组件的方法,因为我知道前两部分的长度总是固定的,但我找不到真正实现这一目标的方法

它已经到了让人觉得我的头撞到了墙上的地步。因此,我需要更熟悉Java和Socket编程的人就如何处理这个问题提供建议

我当前的代码

public class ImageLabeler {
/**
 * @param args
 */
public static void main(String[] args) {
    String IP = args[0];
    System.out.println(IP + "\n");

    String port = args[1];
    System.out.println(port + "\n");

    Socket clientSocket;
    DataOutputStream outToServer = null;
    BufferedReader inFromServer = null;

    String serverResponse;



    try {
        clientSocket = new Socket(IP, Integer.parseInt(port));
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        System.out.println("Connection success\n");
    } catch (IOException ex) {
        System.out.println("Connection failed\n");
        System.exit(0);
    }

    PrintWriter writer = new PrintWriter(outToServer, true);

    try {
        //outToServer.writeBytes("USER bilkentstu\\n");
        //outToServer.flush();
        //System.out.println("check\n");
        writer.println("USER bilkentstu");

        serverResponse = inFromServer.readLine();
        System.out.println(serverResponse + "\n");

        writer.println("PASS cs421f2019");

        //outToServer.writeBytes("PASS cs421f2019\\r\\n");
        //outToServer.flush();

        serverResponse = inFromServer.readLine();
        System.out.println(serverResponse + "\n");

        writer.println("IGET");
        //This is where I need to handle the incoming Image messages.

        writer.println("EXIT");
    } catch (IOException ex) {
        Logger.getLogger(ImageLabeler.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(0);
}

}不要使用缓冲读取器。您需要编写从套接字的输入流中读取字符串的代码,每次读取一个字节。

Yep。我设法弄明白了。最终将inputStreamReader(进入BufferedReader)和DataInputStream绑定到套接字自己的inputStream。当我收到图像文件响应时使用DataInputStream,其他所有内容都使用bufferedReader,因为只有图像文件响应需要逐字节读取。