在Java TCP套接字上发送任意长的字符串

bib*_*yde 0 java sockets string networking tcp

我有一个Android应用程序通过TCP套接字与我写的服务器进行通信.我现在使用的读取和写入输出的方法适用于较小的字符串(最大60kB),但是当字符串比这个字符串长得多时,我会抛出异常.以下是我对服务器和客户端的相关部分:

服务器:

            DataInputStream dis = null;
            DataOutputStream dos = null;

            try {
                    dis = new DataInputStream(server.getInputStream());
                    dos = new DataOutputStream(server.getOutputStream());

                    String input = "";
                    input = dis.readUTF();
                    handle_input info = new handle_input(input, id);
                    String xml = info.handle();

                    dos.writeUTF(xml);

                    server.close();

            } 
Run Code Online (Sandbox Code Playgroud)

客户:

        Socket socket = null; 
        DataOutputStream dos = null;
        DataInputStream dis = null;
        Boolean result;

        try {
            socket = new Socket(ip, port);
            dos = new DataOutputStream(socket.getOutputStream());
            dis = new DataInputStream(socket.getInputStream());
            dos.writeUTF(the_text);
            String in = "";
            while (in.equals("")) {
                in += dis.readUTF();
            }
        }
Run Code Online (Sandbox Code Playgroud)

如何修改它以处理潜在的巨大字符串?我一直在四处寻找,似乎无法找到明确的答案.

谢谢.

Ste*_*n C 6

If you look at the javadoc for writeUTF(), it is obvious that the method can only handle strings with up to 65535 encoded bytes. (The encoded form starts with 2 bytes that give the string byte count).

Your choices are:

  • send the String as an array of characters extracted using String.toCharArray(),
  • use String.getBytes("UTF-8") to UTF8-encode the string explicitly and send the resulting bytes, or
  • split it into smaller substrings, send them using writeUTF8, and splice them back together at the other end.

All of these will entail preceding the actual data with a count to tell the other end how much to expect/read.

The other approach is to send/receive the data as text using a Writer and Reader instead of DataOutputStream and DataInputStream.