简体   繁体   中英

Multiple Input/Output streams in Java?

I ran into a problem while using input/output streams in Java. My thought was to have a DataInputStream to handle receiving text and a PrintStream to pass messages to the server from the server and object(output/input)streams to handle passing piece movements and current board image.

My problem is that the code hangs while it is trying to create the ObjectInputStream in the code below. Is this because I am trying to have multiple input and output streams? If so is there any possible fix I could use?

       Socket sock = new Socket("127.0.0.1", 1716);
       input = new DataInputStream(sock.getInputStream());
       printer = new PrintStream(sock.getOutputStream());

       System.out.println("Test 1");
       zelda = new ObjectInputStream(sock.getInputStream());
       System.out.println("Test 2");
       link = new ObjectOutputStream(sock.getOutputStream());
       System.out.println("Test 3");

I have a lot of Legend of Zelda references in my server source code and the code is rather large. The previous source code is for the client and although the server connects here is where I call ObjectOutputStream.

    ObjectOutputStream ganandorf;

    for(int i = 0; i < clients.size(); i++)
    {
       try
       {
            ganandorf = new ObjectOutputStream(clients.get(i).getOutputStream());
            ganandorf.write(1);
            ganandorf.flush();
            ganandorf.writeObject(something);
            ganandorf.flush();
       }

Don't try to use two different kinds of streams/readers/writers on the same underlying connection. You will encounter buffering issues at both ends that make it basically impossible.

I would use ObjectInputStream and ObjectOutputStream and just write objects.

The constructor of ObjectInputStream blocks until it receives the header that is written by the constructor of ObjectOutputStream , so if you are constructing both you must construct the ObjectOutputStream first. You don't need to write anything and you don't need to flush it either, it does that itself.

I think you can only ask for 1 inputStream reference:

InputStream baseInputStream = sock.getInputStream();
input = new DataInputStream(baseInputStream);
zelda = new ObjectInputStream(baseInputStream);

same goes for outputStreams

在其他端口上打开套接字,然后使用该套接字创建新的流。

我从来没有发现ObjectInputStream发生了什么,但是我切换到DataInputStream,并且我当前正在修改我的代码,因此它将片段名称,x位置和y位置发送到一个字符串中,该字符串将在客户端分解,董事会将相应地修改

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