简体   繁体   English

Java套接字:以两种不同方式逐一读取/写入流

[英]Java Sockets: read/write stream in two different ways one by one

About java.net.Socket and java.io. 关于java.net.Socket和java.io。 The server wants to send messages to a client, first use ObjectOutputStream to write(read, for client) an object, and then use BufferedWriter to write(read, for client)。 服务器要向客户端发送消息,首先使用ObjectOutputStream写入(为客户端读取)一个对象,然后使用BufferedWriter写入(为客户端读取)。

I can make it if I use ObjectXXXStream only or BufferedXXX only, but can't use them together on one stream. 如果仅使用ObjectXXXStream或仅使用BufferedXXX ,但不能在一个流中一起使用它们,则可以实现。 What should I do? 我该怎么办?

server: 服务器:

oos = new ObjectOutputStream(client.getOutputStream());
oos.writeObject(dc);
// oos.close();

bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));          

bw.write("hahaha");
bw.flush();

while(true){
    line=br.readLine();
    if(line != null){
        ExecuteInput(line);
    }
}   

in client: 在客户中:

ois = new ObjectInputStream(socket.getInputStream());
XXX dc = (XXX) ois.readObject();
// ois.close();

String line;
while(true){
    try {
        // System.out.println("000000");
        line=br.readLine();
        // System.out.println("111111");
        if(line != null)
            System.out.println("aaaa "+line);
    } catch (IOException e) {
        System.out.println("222222");
        e.printStackTrace();
    }
}

You would use the ObjectOutputStream for both write operations. 您将对两个写入操作都使用ObjectOutputStream You cannot have 2 different types of streams for one socket, so you'd choose the most functional. 一个套接字不能有2种不同类型的流,因此您将选择功能最强大的流。

Although, I would question if sending objects is actually needed. 虽然,我会质疑是否确实需要发送对象。 You could instead send the state of the object and an "opcode" specifying what should be done with that state. 您可以改为发送对象的状态和“操作码”,以指定应使用该状态执行的操作。 But I don't know the purpose of dc , so I couldn't confirm 但是我不知道dc的用途,所以我无法确认

You can't use multiple streams/readers/writers on a socket when one or more of them is buffered, and both BufferedWriter and ObjectOutputStream are buffered. 当一个或多个缓冲区被缓冲并且BufferedWriterObjectOutputStream都被缓冲时,您不能在套接字上使用多个流/读取器/ ObjectOutputStream器。

Just use ObjectOutputStream() and either send everything as objects or else send the strings via writeUTF() , which means you have to read the strings with readUTF(). 只需使用ObjectOutputStream()并将所有内容作为对象发送,或者通过writeUTF()发送字符串,这意味着您必须使用readUTF().读取字符串readUTF().

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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