【问题标题】:Reassign input/output stream?重新分配输入/输出流?
【发布时间】:2012-12-02 11:02:05
【问题描述】:

我正在尝试使用 android 中的库连接到终端仿真器,这将连接到串行设备,并且应该向我显示发送/接收的数据。要附加到终端会话,我需要提供 inputstreamsetTermIn(InputStream)outputstreamsetTermOut(OutputStream)

我在onCreate() 中初始化并附加了一些流,这些只是初始流,并没有附加到我想要发送/接收的数据。

private OutputStream bos;
private InputStream bis;

...

byte[] a = new byte[4096];
bis = new ByteArrayInputStream(a);
bos = new ByteArrayOutputStream();
session.setTermIn(bis);
session.setTermOut(bos);
/* Attach the TermSession to the EmulatorView. */
mEmulatorView.attachSession(session);

我现在想在发送和接收数据时将流分配给数据,但我认为我做错了。在我每次按回车时调用的sendData() 方法中,我有:

public void sendData(byte[] data)
{
        bos = new ByteArrayOutputStream(data.length);         
}

onReceiveData() 方法中,每次通过串行接收数据时调用:

public void onDataReceived(int id, byte[] data)
{
        bis = new ByteArrayInputStream(data);           
}

我在终端屏幕上看不到任何数据,但我通过串行成功发送和接收数据。所以我的问题是,我应该在每次发送和接收数据时设置流还是只设置一次。我还需要将它们再次附加到终端会话mEmulatorView.attachSession(session) 某处还是应该自动将新流发送到屏幕?

我的理论是我的终端连接到旧流,这就是为什么我无法在终端屏幕上看到数据。这是正确的吗?

我尝试使用布尔值和 if 语句在每个方法中设置一次新的输入/输出流,但随后我在 logcat 中收到警告消息

RuntimeException 'sending message to a Handler on a dead thread'

我已经根据已回答将其编辑为 write 和 rad,但我注意到该库有自己的 write 方法来将数据提供给终端,所以我什至不知道流的用途是什么情况下,我需要这个写来写到模拟器吗?

public void write(byte[] data,
              int offset,
              int count)
Write data to the terminal output. The written data will be consumed by the emulation     client as input.
write itself runs on the main thread. The default implementation writes the data into a     circular buffer and signals the writer thread to copy it from there to the OutputStream.

Subclasses may override this method to modify the output before writing it to the  stream, but implementations in derived classes should call through to this method to do the  actual writing.

Parameters:
data - An array of bytes to write to the terminal.
offset - The offset into the array at which the data starts.
count - The number of bytes to be written.

【问题讨论】:

  • 您想通过不同的流发送每条数据还是什么?如果是,那么这是个坏主意,你应该使用已经创建的流的 bos.Read() 和 bis.Write()。
  • 我明白你的意思谢谢,虽然它是 bos.write 等,但你把它们弄混了。 :) 我现在尝试过,但屏幕上仍然没有出现任何内容。另外,当我在开始时手动将 inputstream 设置为 4096 字节时,这不是问题,不会填满吗?还是因为它是一个流而这个初始数字根本无关紧要?

标签: java android stream inputstream outputstream


【解决方案1】:

java中的对象是通过引用传递的,因此如果你这样做

bos = new ByteArrayOutputStream(data.length)

您实际上是在丢弃以前的输出流并创建一个新的输出流。

尝试保持对输入和输出流的引用并将数据写入其中,例如:

bos.write(data);

【讨论】:

  • 现在尝试了机器人读写,仍然没有变化,但我想我更倾向于现在,谢谢。仍然令人讨厌的是什么都没有显示出来:(当我在开始时将 inputstream 设置为 4096 字节时,这个 bos.write(data) 会覆盖那个固定数字吗?还是因为它是一个流,所以这有关系吗?你 4096 字节是真的什么都没有?
  • @Mateusz 我编辑了操作以注意库有它自己的写入来写入终端的输入。所以我真的很困惑该怎么做。我要么将流传递给正常的输入/输出流写入方法,但终端上什么也没有出现。或者我使用库的 write 方法,我不知道如何将 bos/bis 连接到这些。 bos.session.write(数据);不起作用或 session.bos.write(data),这只是错误的语法吗?
猜你喜欢
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 2014-01-06
  • 1970-01-01
相关资源
最近更新 更多