java - 如果服务器没有客户端 TCP 使用 java 请求的文件,如何显示错误消息

标签 java sockets tcp

我必须为 TCP 客户端/服务器编写 java 项目。代码的目标是客户端向服务器询问文件。如果文件可用,它将被保存到客户端目录中,并显示文件已找到并保存的消息,否则,文件未找到。

当文件在服务器目录中时代码有效,它将保存在客户端目录中,但如果文件不可用,它将在服务器端显示消息文件不可用,但在客户端它将保存一个新的带有不可用文件名的空文件,并向文件发送消息

你能帮忙吗

我有服务器代码

import java.io.*;
import java.net.*;
import java.util.*; 

//********************
public class Server
{
   static ServerSocket  ServSock;
   static int           QLen = 6;

   //***
   public static void main(String args[])
   {
      try
      {
         //*** establish server socket
         ServSock = new ServerSocket(Integer.parseInt(args[0]), QLen);

         while (true)
         {
               //***  accept a client
               Socket Sock = ServSock.accept();

               //*** pass the client to a new thread
               new Worker(Sock).start();
          }
      }
      catch(IOException e)
          {System.out.println(e);}
    }
}





//*************************
class Worker extends Thread
{
   Socket          Sock;
   PrintWriter     PW;
   BufferedReader  DIS;
   String          Question = "Enter the file name to transfer from server:";


   //**************
   Worker(Socket S)
   {Sock=S;}


   //**************
   public void run()
   {
     try
     {
        //*** thread identifies itself
        System.out.println("Thread: " + getName());


        //*** auto-flush
        //*** set up socket I/O streams
        PW = new PrintWriter (new BufferedWriter (new OutputStreamWriter(Sock.getOutputStream())),true);
        DIS  = new BufferedReader (new InputStreamReader (Sock.getInputStream()));



        //*** send server question
        PW.println(Question);


        //*** wait for client response
        String R = DIS.readLine();
        Scanner in = null; 
         try{
                BufferedOutputStream put=new BufferedOutputStream(Sock.getOutputStream());
                 BufferedReader st=new BufferedReader(new InputStreamReader(Sock.getInputStream()));
                  String str = "/Users/Batool/Desktop/HW/Server/";
                 String path = str + R; 
                 System.out.println("The requested file is path: "+path);
                 System.out.println("The requested file is : "+R);

                 File f=new File(path);
                  System.out.println(f.isFile());


                 if(f.isFile())
                 { 

            //System.out.println("inside if");

                     FileInputStream fis=new FileInputStream(f);
             System.out.println("File transfered");
System.out.println("———————————————————————————————");

                   byte []buf=new byte[1024];
                     int read;


                     while((read=fis.read(buf,0,1024))!=-1)
                     {
                         put.write(buf,0,read);
                         put.flush();
                     }




        }//end if 



                else{ System.out.println("File not found");
              System.out.println("———————————————————————————————");}//end else   

            }//end try


         catch(FileNotFoundException e)
            {
               System.out.println(e.getMessage());
               //System.exit(0);

             }//end catch


        //*** close this socket connection
        Sock.close();
        }

     catch(IOException e)
        {System.out.println(e);}
   }
}

我有客户端代码

import java.io.*;
import java.net.*;
import java.util.*; 

public class Client
{
   static Socket          sock;
   static PrintWriter     pw;
   static BufferedReader  br;
   static String          response = "";

   //************************************
   public static void main(String args[]) throws IOException
   {
      //*** establish connection to remote server
      sock = new Socket(args[0],
                       Integer.parseInt(args[1]));  //*** provide server name & port


      //*** set up socket I/O streams
      pw = new PrintWriter (new BufferedWriter (new OutputStreamWriter(sock.getOutputStream())),true);
      br  = new BufferedReader (new InputStreamReader (sock.getInputStream()));


      //*** wait for server question
      String r = br.readLine();    //*** THIS IS A BLOCKING CALL
      System.out.println("Server asks: " + r);

      //*** respond to server
      /*Scanner in = new Scanner(System.in); 
     String s = in.nextLine();
      pw.println(s);
      pw.flush(); 
     */
     Socket s=null;
        BufferedInputStream get=null;
        PrintWriter put=null;
        try
        { 
             get=new BufferedInputStream(sock.getInputStream());
            put=new PrintWriter(sock.getOutputStream(),true);

            String f;
            int u;
            //System.out.println("Enter the file name to transfer from server:");
            DataInputStream dis=new DataInputStream(System.in);
            f=dis.readLine();
            put.println(f);
            File f1=new File(f);
            String str = "/Users/Batool/Desktop/HW/Client";
            FileOutputStream  fs=new FileOutputStream(new File(str,f1.toString()));

        System.out.println(new File(str,f1.toString()));

System.out.println(f1.isFile());

            byte jj[]=new byte[1024];

            while((u=get.read(jj,0,1024))!=-1)
            { 
                fs.write(jj,0,u);
            } 
            fs.close();
            System.out.println("File received");
System.out.println("———————————————————————————————");
             sock.close();
        }catch(Exception e)
        {
                       System.out.println("File not found");
            System.out.println("———————————————————————————————");
            e.printStackTrace();
            System.exit(0);
        }


      //*** close this socket connection
      //sock.close();
   }
}

最佳答案

基本上您需要实现一个协议(protocol)

客户端询问服务器:你有文件X吗?

a) 服务器说:是的,我为你提供了 xyz 字节,md5sum 是 zyx

然后您的客户要求该文件;它可以验证它获得了正确的字节数并且没有发生传输错误。 (当然你不需要那个验证部分;但根据你的上下文,这些也是你应该考虑到位的东西)

b) 服务器说:不,我没有那个文件

然后您的客户端会向其用户提供一条错误消息。

换句话说:服务器只是读取文件并推出字节是行不通的!

您想将您的服务器 变成提供服务 的东西。而一个服务有一个契约,比如“输入”和“输出”。服务需要“协商”接下来应该发生什么的方法。在您当前的解决方案中,发生的一切都是硬编码的 - 这意味着已经有一个协议(protocol),但该协议(protocol)是由您放入代码中的指令定义的!

关于java - 如果服务器没有客户端 TCP 使用 java 请求的文件,如何显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171447/

相关文章:

java - 我的对象未打印

java - Objectify 不返回新数据

TCP 拥塞窗口大小..?

C# 通过 TCP 使用 SSL 发送请求不起作用

c - 如何在 Linux 中将套接字链接到 PID?

java - 服务器如何获取客户端的IP和端口号TCP?

java - 如何在 WSDL 中添加 xsd

java - Spring Boot OAuth2 单点注销(注销)

c# - 在单台计算机上进行套接字编程?

c - 将 UDP 数据包识别为不同的连接