TCP中使用ObjectOutputStream传输数据对象抛出**Connection reset**的异常。

来源:互联网 发布:imap smtp 端口 编辑:程序博客网 时间:2024/06/06 01:53

特别注意:
在使用ObjectOutputStream基于TCP传输时客户端在发送完ObjectOutputStream oos = new ObjectOutputStream(ops);
oos.writeObject(p);一定要记得调用
oos.flush();
socket.shutdownOutput();flush()是为了刷新缓冲区,socket.shutdownOutput()用来关闭Socket的输出流。通知服务器端自己已经发送完了否则在服务器端调用`ObjectInputStream ois = new ObjectInputStream(s.getInputStream());抛出Connection reset的异常。因为在没有调用shutdownOutput()时,服务器端收到流后并不知道何时客户端发完消息,就会立刻关闭socket,就会造成服务器已经关闭Socket,但是客户端依旧在发送数据,服务器就会抛出异常了。

服务器端代码:

public static void main(String[] args) throws IOException, ClassNotFoundException {        serverSoctetTell s = new serverSoctetTell();         s.GetAndSendPerson();    }    public void GetAndSendPerson() throws IOException, ClassNotFoundException {        ServerSocket socket = new ServerSocket(8899);        System.out.println("服务器端已启动,准备接收数据对象*****");        Socket s = socket.accept();        if (!s.isClosed()) {            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());            Person pul = (Person) ois.readObject();            System.out.println(pul.toString());            socket.close();        } else {            System.out.println("服务器已经关闭");        }    }

客户端代码

public static void main(String[] args) {        clientSocketTell cst = new clientSocketTell();        Person p = new Person("吴俊杰", "123456");         try {         cst.GetAndSendPerson(p);         } catch (ClassNotFoundException | IOException e) {         // TODO Auto-generated catch block         e.printStackTrace();         }    }    public void GetAndSendPerson(Person p) throws IOException, ClassNotFoundException {        InetAddress address = InetAddress.getByName("127.0.0.1");        Socket socket = new Socket(address, 8899);        System.out.println("客户端准备发送数据:" + p.toString());        OutputStream ops = socket.getOutputStream();        ObjectOutputStream oos = new ObjectOutputStream(ops);        oos.writeObject(p);        oos.flush();        socket.shutdownOutput();    }
0 0
原创粉丝点击