我需要按运行时更改套接字流。首先,我需要使用 ObjectStreams:
Socket socket = ...
InputStream networkInput = socket.getInputStream();
OutputStream networkOutput = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(networkOutput);
oos.flush();
ObjectInputStream ois = new ObjectInputStream(networkInput);
//use the object-streams
然后我需要更改为其他流
oos.close();
ois.close();
XYOutputStream xyos = new XYOutputStream(networkOutput);
xyos.flush();
XYInputStream xyis = new XYInputStream(networkInput);
但是如果我使用上面的代码,套接字会关闭,我会得到一个
java.net.SocketException: Socket closed
如果我使用
socket.shutdownInput();
socket.shutdownOutput();
而不是关闭旧流,我得到一个
java.net.SocketException: interrupted data transfer (broken pipe)
当我尝试初始化我的 XYStreams 时。
我认为
您不需要关闭流。我写了一个使用文件系统和 PrintStream 的示例,但它应该与套接字和输出流相同。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class TestStream {
public static void main (String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("test.txt");
PrintStream p1 = new PrintStream(fos, false);
PrintStream p2 = new PrintStream(fos, false);
p1.print("Test");
p1.flush();
p2.print(100);
p2.flush();
fos.close();
}
}