简体   繁体   中英

change stream to java socket

I need to change my stream of the socket by runtime. First i need to use 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

Then i need to change to some other stream

oos.close();
ois.close();
XYOutputStream xyos = new XYOutputStream(networkOutput);
xyos.flush();
XYInputStream xyis = new XYInputStream(networkInput);

But if i use the upper code, the socket is closed and i get a

java.net.SocketException: Socket closed

If i use

socket.shutdownInput();
socket.shutdownOutput();

instead of closing the old streams i get a

java.net.SocketException: interrupted data transfer (broken pipe)

when i try to initialize my XYStreams.

I do not think that you need to close the stream. I have written an example that uses the file system and the PrintStream, but it should be the same with a socket and your output streams.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM