java - PrintWriter 只发送部分字符串 Java

标签 java sockets printwriter println

我正在用 Java 做一些套接字工作,并试图对它发送的数据进行编码。 该部分工作正常,但由于某种原因,它不会通过套接字发送整个编码字符串。好像分3部分送。

客户端从 MyBufferedReader 类(在下面)执行一个简单的 readLine(),服务器像这样发送它:

    private void sendFile(File f, String dest){ //The file to be sent and the destination
        System.out.println("Sending file started..");

        try {
            this.out.println("CMD MKFILE " + dest + "/" + f.getName());
            //TODO send the file
        }catch(Exception e){
            e.printStackTrace();
        }
    }

客户端收到: CMD MKFILE C:\Users\Lolmewn\Documents\test/dir/n/linebrea 然后再读取 k!.txt

MyBufferedReader 和 MyPrintWriter 类如下所示:

MyBufferedReader:

    @Override
    public String readLine() throws IOException {
        String read = super.readLine();
        System.out.println("UNDEC: " + read);
        try {
            System.out.println("DEC: " + decode(read));
            return decode(read);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return read;
    }

    public static String decode(String b) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(b.getBytes("UTF-8"));
        InputStream b64is = MimeUtility.decode(bais, "base64");
        byte[] tmp = new byte[b.length()];
        int n = b64is.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return new String(res);
     }

和 MyPrintWriter:

    private String hash(String x) {
        try {
            return encode(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return x;
    }

    public static String encode(String b) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b.getBytes("UTF-8"));
        b64os.close();
        return new String(baos.toByteArray());
     }

这是怎么回事,我该如何解决?

请注意:我正在对这些套接字进行异步工作,这意味着我不能只使用 while(read != null) 语句。这会导致其他不应该存在的数据也存在。

最佳答案

首先撇开这一点:如果您从多个线程/客户端发送消息,那么您应该为它们中的每一个打开一个套接字(就像 accept() 那样),这样来自不同客户端的消息就不能相互交错。

现在我假设每个套接字只有一个客户端(合理):

I can't just use a while(read != null)

你必须实现一个简单的协议(protocol),你可以用它来区分一条消息和另一条消息,例如如果永远不能成为数据的一部分,则使用 0 字节,或者在消息的长度前加上消息的前缀,然后同时发送;这样您的服务器就可以区分一条消息和另一条消息。

关于java - PrintWriter 只发送部分字符串 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9260649/

相关文章:

java - 如何引用 JTABLE 的第一列并为该列中单击的每一行添加操作?

java - GUI swing 多线程应用程序中的代码结构

java - 为什么我无法打破外层 for 循环?

java - 如何将 HSSF 行保存为字符串 java POI

java - 如何使用 Spring Boot 在不同端口启动 Web 容器和 Netty 服务器?

node.js - 服务器端的浏览器唯一字段

javascript - 如何在 Node.js 中捕获原始请求

java - 为什么空异常运行时错误出现在 line `outputFile.println("Package : "+ letter);` ?

java - PrintWriter 默认位置

java - 如何将 PrintWriter 的结果保存在文件中而不是将其显示在控制台中