Streams通过Socket

uml*_*uml 0 java sockets exception stream

我正在编写服务器客户端应用程序.客户端通过不同的流将某种数据发送到服务器.一旦我在主方法中放置这样的流,程序什么都不做; 空控制台也不例外:

try {
                socket = new Socket("localhost", 4050);                     
                din = new DataInputStream(socket.getInputStream());
                oin = new ObjectInputStream(socket.getInputStream());
                dout = new DataOutputStream(socket.getOutputStream());                     


            } catch (UnknownHostException e) {              
                System.out.println("Exception: the host is unknown");
            } catch (IOException e) {
                System.out.println("I/O exception thrown by socket");
            }
Run Code Online (Sandbox Code Playgroud)

一旦我oin = new ObjectInputStream(socket.getInputStream());从main方法的那一部分中删除了这个流 ,程序就会抛出EOFException或连接重置异常.在上面的代码中有什么特别之处,程序什么也不做,并且没有例外?

将上述流放入单独的方法后

private static MessageObject readObject(){
        MessageObject mo = null;

        try{
             oin = new ObjectInputStream(socket.getInputStream());
             mo = (MessageObject)oin.readObject();

        } 
        catch(IOException e){
            System.err.println(e.getCause());
        }
        catch(ClassNotFoundException e){
            System.err.println(e.getCause());
        }
        return mo;
    }
Run Code Online (Sandbox Code Playgroud)

它抛出了这个异常:

Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.DataInputStream.readBoolean(Unknown Source)
    at Server.main(Server.java:77)
Run Code Online (Sandbox Code Playgroud)

在服务器上,它位于if分支上:

if (din.readBoolean()) {

        ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
        MessageObject o = (MessageObject)oin.readObject();

        // server saves the whole thing
        MessageDB.add(o);

    }
Run Code Online (Sandbox Code Playgroud)

我无法将所有代码放在这里,这是我的任务.

哎呀,对不起,找到了错误.一些逻辑错误,服务器期待一些输入,但客户端拒绝发送它.

use*_*421 7

你在这里犯了几个错误.

  1. 您在同一个套接字上使用多个流.不要这样做,他们只会互相混淆.当你需要对象I/O时,只需使用一个ObjectInputStreamObjectOutputStream所有的东西.

  2. 施工顺序错误.你必须建造ObjectOutputStream ObjectInputStream,在两端.

  3. 您正在使用具有不同生命周期的流.你还没有遇到问题,但最终会导致问题StreamCorruptedException.两端使用相同的插座ObjectInputStreamObjectOutputStream插座的使用寿命.

  4. 您可能还需要阅读Javadoc ObjectOutputStream.reset().writeUnshared()了解它们的作用,以及为什么您可能需要调用它们中的一个或另一个.