Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 多个ObjectOutputStream出错&;ObjectInputStream(套接字已关闭)_Java_Sockets - Fatal编程技术网

Java 多个ObjectOutputStream出错&;ObjectInputStream(套接字已关闭)

Java 多个ObjectOutputStream出错&;ObjectInputStream(套接字已关闭),java,sockets,Java,Sockets,我正在尝试制作一个套接字程序来同步两台电脑上的文件。所以,基本上,我想先做一个单向同步。所以发生的是 服务器和客户端通过套接字连接在一起。(好的) 服务器通过ObjectOutputStream发送他拥有的文件列表,客户端通过ObjectOutputStream接收它。(好的) 客户端比较文件列表,并将他没有的文件发送回服务器(通过ObjectOutputStream)。(好的) 服务器将丢失的文件发送到客户端。(这里有问题) 我的错误在服务器端,它显示: java.net.SocketExce

我正在尝试制作一个套接字程序来同步两台电脑上的文件。所以,基本上,我想先做一个单向同步。所以发生的是

  • 服务器和客户端通过套接字连接在一起。(好的)
  • 服务器通过ObjectOutputStream发送他拥有的文件列表,客户端通过ObjectOutputStream接收它。(好的)
  • 客户端比较文件列表,并将他没有的文件发送回服务器(通过ObjectOutputStream)。(好的)
  • 服务器将丢失的文件发送到客户端。(这里有问题)
  • 我的错误在服务器端,它显示:

    java.net.SocketException: Socket is closed
    at java.net.Socket.getOutputStream(Unknown Source)
    at ee4210.TcpServer$ConnectionRequestHandler.run(TcpServer.java:116)
    at ee4210.TcpServer.handleClientRequest(TcpServer.java:80)
    at ee4210.TcpServer.startServer(TcpServer.java:72)
    at ee4210.TcpServer.main(TcpServer.java:39)
    
    我相信它与ObjectOutputStream和ObjectInputStream有关,因为如果我不关闭ObjectOutputStream或ObjectInputStream,它可以工作

    客户端是否可以同时使用ObjectOutputStream和ObjectInputStream来发送/接收对象?类似地,服务器也可以同时拥有这两种功能吗

    谢谢你的帮助。抱歉发了这么长的邮件。我希望尽可能详细

    我的客户代码:

    package ee4210;
    
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;public class TcpClient{
    static ObjectOutputStream out;
    static ObjectInputStream in;
    String message;
    int portNo=2004;
    static Socket _socket = null;   
    InetAddress host = null;
    static LinkedList destinationfiles = new <String>LinkedList();
    static LinkedList sourcefiles = new <String>LinkedList();
    static LinkedList missingfiles = new <String>LinkedList();
    String filename=null;
    
    TcpClient(){}
    
    public static void listFilesForFolder(final File folder) { //no need to read this
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                //System.out.println(fileEntry.getName());
                destinationfiles.add(fileEntry.getName());
            }
        }
    }
    
    public static void getListfromPeer() {
        try {
            in=new ObjectInputStream(_socket.getInputStream());
            sourcefiles = (LinkedList) in.readObject();
            //in.close(); //if i close, got error
        } catch (ClassNotFoundException | IOException classNot) {
            System.err.println("data received in unknown format");
        }
    
    }
    
    public static void compareList() {
        // go through each of the peer's filename, check against urs. If dont
        // have, download
        ListIterator iter = sourcefiles.listIterator();
        String filename;
        while (iter.hasNext()) {
            // System.out.println(iter.next());
            filename=(String) iter.next();
            if (!destinationfiles.contains(filename)) //file cannot be found
            {
                missingfiles.add(filename);
            }
        }
    
    }
    
    public static void main(String[] args) {
        /*Check if directory exist, create one if doesnt exit*/
        File theDir = new File("src/ee4210/files");
    
        // if the directory does not exist, create it
        if (!theDir.exists()) {
            System.out.println("creating directory..");
            boolean result = theDir.mkdir();
            if (result) {
                System.out.println("Successfully created directory");
            }
    
        }
        /*Get the list of files in that directory and store the names in array*/
        listFilesForFolder(theDir);
    
        /*Connect to peer*/
        try {
            new TcpClient().connect();
            //new TcpClient().checkForInput();
    
        } catch (Exception e) {
            System.out.println("Something falied: " + e.getMessage());
            e.printStackTrace();
        }
    
    }
    
    public void connect() throws IOException 
    {
    
        try {
            host = InetAddress.getLocalHost();
            //_socket = new Socket(host.getHostName(), portNo);
            _socket = new Socket("172.28.177.125", portNo);
            //System.out.println(host.getHostAddress()); //get the IP address of client
    
            /*Get list from peer and compare list*/
            getListfromPeer(); //receive from Server
            compareList();
            System.out.println(missingfiles);
    
            /*Send to server the list of missing files*/
    
            do
            {
                //busy wait till socket is open
            }while (_socket.isClosed());
            out = new ObjectOutputStream(_socket.getOutputStream());
            out.flush();
            out.writeObject(missingfiles);
            out.flush();
            System.out.println("Client have finished sending missing linkedList over");
            out.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    
    包ee4210;
    导入java.io.*;
    导入java.net。*;
    导入java.util.*;公共类TcpClient{
    静态对象输出流输出;
    静态对象输入流输入;
    字符串消息;
    int-portNo=2004;
    静态套接字_Socket=null;
    InetAddress主机=null;
    静态LinkedList destinationfiles=新LinkedList();
    静态LinkedList sourcefiles=新LinkedList();
    静态LinkedList missingfiles=新建LinkedList();
    字符串文件名=null;
    TcpClient(){}
    publicstaticvoidlistfilesforfolder(最终文件文件夹){//无需阅读此文件
    对于(最终文件条目:folder.listFiles()){
    if(fileEntry.isDirectory()){
    listFilesForFolder(文件条目);
    }否则{
    //System.out.println(fileEntry.getName());
    add(fileEntry.getName());
    }
    }
    }
    公共静态void getListfromPeer(){
    试一试{
    in=newObjectInputStream(_socket.getInputStream());
    .readObject()中的sourcefiles=(LinkedList);
    //in.close();//如果我关闭,则返回错误
    }捕获(ClassNotFoundException | IOException classNot){
    System.err.println(“以未知格式接收的数据”);
    }
    }
    公共静态空比较列表(){
    //检查每个对等文件的文件名,对照urs进行检查。如果没有
    //下载
    ListIterator iter=sourcefiles.ListIterator();
    字符串文件名;
    while(iter.hasNext()){
    //System.out.println(iter.next());
    filename=(字符串)iter.next();
    如果(!destinationfiles.contains(filename))//找不到文件
    {
    missingfiles.add(文件名);
    }
    }
    }
    公共静态void main(字符串[]args){
    /*检查目录是否存在,如果不存在则创建一个*/
    File theDir=新文件(“src/ee4210/files”);
    //如果目录不存在,请创建它
    如果(!theDir.exists()){
    System.out.println(“创建目录…”);
    布尔结果=dir.mkdir();
    如果(结果){
    System.out.println(“已成功创建目录”);
    }
    }
    /*获取该目录中的文件列表并将名称存储在数组中*/
    文件夹列表文件(目录);
    /*连接到对等*/
    试一试{
    新建TcpClient().connect();
    //新建TcpClient().checkForInput();
    }捕获(例外e){
    System.out.println(“有问题:+e.getMessage());
    e、 printStackTrace();
    }
    }
    public void connect()引发IOException
    {
    试一试{
    host=InetAddress.getLocalHost();
    //_套接字=新套接字(host.getHostName(),portNo);
    _插座=新插座(“172.28.177.125”,端口号);
    //System.out.println(host.getHostAddress());//获取客户端的IP地址
    /*从对等方获取列表并比较列表*/
    getListfromPeer();//从服务器接收
    比较列表();
    System.out.println(丢失文件);
    /*向服务器发送丢失文件的列表*/
    做
    {
    //忙等待,直到插座打开
    }而(_socket.isClosed());
    out=newObjectOutputStream(_socket.getOutputStream());
    out.flush();
    out.writeObject(丢失文件);
    out.flush();
    System.out.println(“客户端已完成发送丢失的linkedList”);
    out.close();
    }捕获(例外e){
    e、 printStackTrace();
    } 
    }
    
    }

    服务器代码:

     package ee4210;
    
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    public class TcpServer extends Thread
    {
    ServerSocket providerSocket;
    Socket connection = null;
    static ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    int portNo=2004; //portNo is 2004
    TcpClient tcpclientobject = new TcpClient();
    static LinkedList destinationfiles = new <String>LinkedList();
    static LinkedList missingfiles = new <String>LinkedList();
    
    public static void main(String[] args) 
    {
        /*Check if directory exist, create one if doesnt exit*/
        File theDir = new File("src/ee4210/files");
    
        // if the directory does not exist, create it
        if (!theDir.exists()) {
            System.out.println("creating directory..");
            boolean result = theDir.mkdir();
            if (result) {
                System.out.println("Successfully created directory");
            }
    
        }
        /*Get the list of files in that directory and store the names in array*/
        listFilesForFolder(theDir);
    
        /*Connect*/
        try {
            new TcpServer().startServer();
        } catch (Exception e) {
            System.out.println("I/O failure: " + e.getMessage());
            e.printStackTrace();
        }
    
        /*Rest of the code in run()*/
    
    
    }
    
    public static void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                //System.out.println(fileEntry.getName());
                destinationfiles.add(fileEntry.getName());
            }
        }
    }
    public void startServer() throws Exception {
        ServerSocket serverSocket = null;
        boolean listening = true;
    
        try {
            serverSocket = new ServerSocket(portNo);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + portNo);
            System.exit(-1);
        }
    
        while (listening) {
            handleClientRequest(serverSocket);
        }
    
        serverSocket.close();
    }
    
    private void handleClientRequest(ServerSocket serverSocket) {
        try {
            new ConnectionRequestHandler(serverSocket.accept()).run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    public class ConnectionRequestHandler implements Runnable{
        private Socket _socket = null;
    
        public ConnectionRequestHandler(Socket socket) {
            _socket = socket;
        }
        public void run() {
            System.out.println("Client connected to socket: " + _socket.toString());
    
            /*Send the linkedlist over*/
            try {
                out = new ObjectOutputStream(_socket.getOutputStream());
                //out.flush();
                out.writeObject(destinationfiles);
                out.flush();
                //out.close(); //if I close, will have errors
            } catch (IOException e) {
                e.printStackTrace();
            }
            receiveMissingFileNames(); //this one is still ok
    
            try { //if i put the close here its ok
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            try { 
                out = new ObjectOutputStream(_socket.getOutputStream()); //when I add this line it shows the error
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
        public void receiveMissingFileNames()
        {
            try {
    
                in=new ObjectInputStream(_socket.getInputStream());
                System.out.println("Is the socket connected="+_socket.isConnected());
                missingfiles=(LinkedList) in.readObject();
                System.out.println(missingfiles);
                in.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    包ee4210;
    导入java.io.*;
    导入java.net。*;
    导入java.util.*;
    公共类TcpServer扩展线程
    {
    ServerSocket providerSocket;
    套接字连接=空;
    静态对象输出流输出;
    目标输入流;
    字符串消息;
    int portNo=2004;//portNo是2004
    TcpClient tcpclientobject=新的TcpClient();
    静态LinkedList destinationfiles=新LinkedList();
    静态LinkedList missingfiles=新建LinkedList();
    公共静态void main(字符串[]args)
    {
    /*检查目录是否存在,如果不存在则创建一个*/
    File theDir=新文件(“src/ee4210/files”);
    //如果目录不存在,请创建它
    如果(!theDir.exists()){
    System.out.println(“创建目录…”);
    布尔结果=dir.mkdir();
    如果(结果){
    System.out.println(“已成功创建目录”);
    }
    }
    /*获取该目录中的文件列表并将名称存储在数组中*/
    文件夹列表文件(目录);
    /*连接*/
    试一试{
    新建TcpServer().startServer();
    }捕获(例外e){
    System.out.println(“I/O故障:+e.getMessage());
    e、 printStackTrace();
    }
    /*run()中的其余代码*/
    }
    公共静态无效列表filesforfolder(最终文件文件夹){
    对于(最终文件条目:folder.listFiles()){
    if(fileEntry.isDirectory()){
    listFilesForFolder(文件条目);
    }否则{
    //System.out.println(fileEntry.getName());
    add(fileEntry.getName());
    }
    }
    }
    公共空间街