将输入流连接到输出流 [英] Connecting an input stream to an outputstream

查看:161
本文介绍了将输入流连接到输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java9中更新: https://docs.oracle.com/javase/9​​/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-

update in java9: https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-

我看到了一些类似的但不是我需要的线程。

I saw some similar, but not-quite-what-i-need threads.

我有一台服务器,它基本上会从客户端,客户端A,并将其逐字节转发给另一个客户端客户端B.

I have a server, which will basically take input from a client, client A, and forward it, byte for byte, to another client, client B.

我想将客户端A的输入流与输出连接起来客户端流B.这可能吗?有什么方法可以做到这一点?

I'd like to connect my inputstream of client A with my output stream of client B. Is that possible? What are ways to do that?

此外,这些客户端正在发送彼此有时间敏感的消息,因此缓冲不会。我不想要500的缓冲区和客户端发送499个字节,然后我的服务器在转发500个字节时保持关闭,因为它没有收到填充缓冲区的最后一个字节。

Also, these clients are sending each other messages, which are somewhat time sensitive, so buffering won't do. I do not want a buffer of say 500 and a client sends 499 bytes and then my server holds off on forwarding the 500 bytes because it hasn't received the last byte to fill the buffer.

现在,我正在解析每条消息以找到它的长度,然后读取长度字节,然后转发它们。我想(并测试)这比读取一个字节并反复转发一个字节更好,因为这将是非常慢的。我也不想使用缓冲区或计时器,因为我在上一段中说过 - 我不希望消息等待很长时间才能通过,因为缓冲区未满。

Right now, I am parsing each message to find its length, then reading length bytes, then forwarding them. I figured (and tested) this would be better than reading a byte and forwarding a byte over and over because that would be very slow. I also did not want to use a buffer or a timer for the reason I stated in my last paragraph — I do not want messages waiting a really long time to get through simply because the buffer isn't full.

这样做的好方法是什么?

What's a good way to do this?

推荐答案

仅仅因为你使用缓冲区而不是t表示流必须填充该缓冲区。换句话说,这应该没问题:

Just because you use a buffer doesn't mean the stream has to fill that buffer. In other words, this should be okay:

public static void copyStream(InputStream input, OutputStream output)
    throws IOException
{
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
}

这应该可以正常工作 - 基本上是读取调用将阻塞,直到某些数据可用,但它不会等到所有可用于填充缓冲区。 (我想它可以,我相信 FileInputStream 通常填充缓冲区,但附加到套接字的流更有可能给你数据立即。)

That should work fine - basically the read call will block until there's some data available, but it won't wait until it's all available to fill the buffer. (I suppose it could, and I believe FileInputStream usually will fill the buffer, but a stream attached to a socket is more likely to give you the data immediately.)

我认为至少首先尝试这个简单的解决方案是值得的。

I think it's worth at least trying this simple solution first.

这篇关于将输入流连接到输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆