Can I change the type of stream I'm using without closing and reopening the socket in Java?
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 Object开发者_运维知识库OutputStream
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.
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();
}
Why do you want the *Stream
to convert to the *Writer
.
You can do what you want to do with *Stream
.
Socket s = new Socket();
DataOutputStream stream = new DataOutputStream( s.getOutputStream() );
byte[] bytes = "INFO".getBytes();
stream.write(bytes);
//....
bytes = "DATA".getBytes();
stream.write(bytes);
精彩评论