通过套接字

时间:2015-11-01 21:24:38

标签: java sockets serversocket

所以我正在学习基本的TCP / IP应用程序,我正试图找出一种接一个发送文本文件的方法。服务器读取的第一行将是文件名,然后将读取文件中的数据。所以我试图探索读取方法,直到第一个文件结束,然后启动另一个流来写另一个文件。我的应用程序在第二次尝试后冻结。所以我不知道问题出在客户端还是服务器端,我不知道如何解决这个问题。

我有获取连接,获取流,关闭连接和处理连接的方法。我只是发布了服务器和客户端的处理连接方法。

客户端:

private void processConnection() throws Exception
    {   //read file
        Path filePath = null;
        try
        {
            filePath = Paths.get(inputpath);
            fileToSend = Files.newInputStream(filePath);
            reader = new BufferedReader(new InputStreamReader(fileToSend));
            //send file name
            output.writeObject(path);
            output.flush();

            //send file data
            String linesToSend = reader.readLine();
            while(linesToSend != null)
            {
                output.writeObject(linesToSend);
                output.flush();
                linesToSend = reader.readLine();
            }
            message = (String)input.readObject();
            display.append("\n" + message);
        }
        catch(NullPointerException e)
        {
            display.append("\nNo file to send.");
        }
    }

SERVER:

private void processConnection() throws IOException
        {
            String message = "Connection successful";
            sendData(message);
                try
                {   
                    //read first line of input for file name
                    String clientInput = (String) input.readObject();
                    //create file path
                    String abFilePath = pathToString + "\\" + clientInput;
                    // create file
                    FileSystem fs = FileSystems.getDefault();
                    Path path = fs.getPath(abFilePath);
                    fileOutput = new BufferedOutputStream(Files.newOutputStream(path, CREATE_NEW));
                    writer = new BufferedWriter(new OutputStreamWriter(fileOutput));
                    //read rest of data
                    String s = (String)input.readObject();
                    while(s != null)
                    {
                        writer.write(s, 0, s.length());
                        s = (String)input.readObject();
                    }
                    writer.close();
                    display.append("\nFile " + clientInput + " was recieved.");
                    message = "\n" + clientInput + " was sent to server.";
                    sendData(message);
                }
                catch(ClassNotFoundException | SocketException e)
                {
                    e.printStackTrace();
                    display.append("\nClient disconnected\n");
                    input = null;
                }
                catch(FileAlreadyExistsException e)
                {
                    display.append("\nFile already exist.");
                }
            }

0 个答案:

没有答案