Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the type of stream I'm using without closing and reopening the socket in Java?

Tags:

java

sockets

I'm doing some socket programming in Java and I'd like to be able to change between using the ObjectOutputStream, the DataOutputStream, and the PrintWriter all within the same socket/connection. Is this possible and what is the best way to do it?

I've tried just creating both types of objects, for example ObjectOutputStream and DataOutputStream, but that doesn't seem to work.

The reason I want to switch between them is to, for example, send a text command "INFO" that signals I'm about to send an object with information or a command "DATA" signalling that I'm about to send data. Any advice on the best way to do this is appreciated.

like image 727
James Avatar asked Dec 12 '25 15:12

James


1 Answers

You can only use one underlying stream type however you can get that data from anywhere.

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));


public static void writeObject(DataOutputStream dos, Serializable obj) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.close();
    dos.writeUTF("OBJECT");
    byte[] bytes = baos.toByteArray();
    dos.writeInt(bytes.length);
    dos.write(bytes);
    dos.flush();
}

public static void writeBytes(DataOutputStream dos, byte[] bytes) {
    dos.writeUTF("BYTES");
    dos.writeInt(bytes.length);
    dos.write(bytes);
    dos.flush();
}

public static void writeText(DataOutputStream dos, String text) {
    dos.writeUTF("TEXT");
    dos.writeUTF(text);
    dos.flush();
}
like image 177
Peter Lawrey Avatar answered Dec 14 '25 03:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!