需要创建从客户端到服务器的简单文件传输

时间:2017-08-16 00:48:03

标签: java eclipse file serversocket

因此,最终产品正在创建一个多客户端到单一服务器类型的程序,其中客户端以xml形式发送文本文件,然后服务器获取文件并解析它以获取信息。我在第一个方,试图只让一个客户端将文件发送到服务器。我这样做(目前)客户端创建一个文本文件(我作为用户将在控制台中输入)并将该文本文件发送到服务器。服务器检查文件是否确实是文本文件,然后用“File received!”响应客户端,但是,客户端类中有些错误,我只是不理解,有人可以帮我解决吗?

这是服务器代码:

package ServerClientTower; 
import java.io.IOException;    
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String file,temp;
        ServerSocket sock1=new ServerSocket(1234);
        Socket ss=sock1.accept();
        Scanner scan=new Scanner(ss.getInputStream());
        PrintStream ps= new PrintStream(ss.getOutputStream());
        file=scan.next();
        if(file.substring(file.length() - 4)==".txt") {
            temp="File retrieved";
            ps.println(temp);
        }
        //temp= number + number;


    }}

以下是客户端代码:

package ServerClientTower;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {

    public static void main(String[] args) throws UnknownHostException, IOException {
        // TODO Auto-generated method stub

        File f= new File("invoice.txt"); //creating .txt file name invoice
        String option,file,temp;
        Scanner scan= new Scanner(System.in);
        Socket sock= new Socket("127.0.0.1",1234);
        Scanner scan2=new Scanner(sock.getInputStream());
        PrintStream print= new PrintStream(sock.getOutputStream());
        System.out.println("Please enter your command using this options \n1.Send (nameofFile).txt\n\n2.Delete\n\n");
        option= scan.nextLine(); //reads input line from user
        String input[]=option.split("\\s");// splits the input, taking in the first user string, and then the second user string
        System.out.println(input[0] +' '+ input[1]); //testing to see if the split actually worked
        if(input[0].contains("Send")) {

             print.println(input[1]);            
        }

       // print.println(number);    
        temp= scan2.next();   //this comes up with an error, though I don't understand why
        System.out.println(temp);

    }

}

出现的错误是:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at ServerClientTower.Client.main(Client.java:29)

所以我不知道是否需要删除temp = scan2.next()或者一起使用不同的方法。

0 个答案:

没有答案