2017-05-27 14 views
0

スクリーンショットを送信します左側のウィンドウ(サーバー)は、この行の正しい出力を実行するのではなく、「ヌル」を出力することである:System.out.println("File " + filename + " downloaded (" + current + " bytes read)");は、ファイル(マルチスレッドのJavaソケット)上のスクリーンショットでプログラムを実行している(右、左、クライアント上のサーバー)</p> <p><a href="https://i.stack.imgur.com/eGbPK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eGbPK.png" alt="enter image description here"></a></p> <p>問題の

次のようにファイル転送通信の流れが起こる:

サーバのユーザは "f"を入力し、サーバはEnterを押し、サーバはファイル名(この場合はtest.txt)を入力し、サーバは入力を、クライアントはファイル名を、クライアントはファイルをサーバに、サーバはファイルを、サーバはプリントラインを出力する。

私の質問は次のとおりです。次のコードを変更して、その印刷行の正しい出力を実行できるようにしますか?

ここでは、サーバー側ここ

public void SendFileName() throws FileNotFoundException 
{ 
     try 
     { 

       //Send the message to the client 
       OutputStream os = socket.getOutputStream(); 
       OutputStreamWriter osw = new OutputStreamWriter(os); 
       BufferedWriter bw = new BufferedWriter(osw); 

       //creating message to send from standard input 
       String newmessage = ""; 

       // input the message from standard input 
       BufferedReader input= new BufferedReader(new InputStreamReader(System.in)); 
       String line = ""; 
       System.out.println("What file do you want?"); 
       line= input.readLine(); 
       newmessage += line + " "; 
       String filename = newmessage; 
       bw.write("filenameistotheright->` " + filename); 
       bw.newLine(); 
       bw.flush(); 

       int maxsize = 9999; 
       int bytesRead; 
       int current = 0; 
       FileOutputStream fos = null; 
       BufferedOutputStream bos = null; 
       Socket sock = null; 

       // receive file 
       byte [] mybytearray = new byte [maxsize]; 
       InputStream is = sock.getInputStream(); 
       fos = new FileOutputStream(filename); 
       bos = new BufferedOutputStream(fos); 
       bytesRead = is.read(mybytearray,0,mybytearray.length); 
       current = bytesRead; 

       while(bytesRead > -1) 
       { 
         bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); 
         if(bytesRead >= 0) 
         { 
          current += bytesRead; 
         } 
       } 

       bos.write(mybytearray, 0 , current); 
       bos.flush(); 
       System.out.println("File " + filename + " downloaded (" + current + " bytes read)"); 
       StandardInput(); 
       // runClientRead(clientArgs); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

上で、それを受けてのコードは、クライアント側

import java.io.*; 
import java.net.Socket; 

public class ClientReceive extends Thread 
{ 

    Socket clientSocket; 
    boolean m_bRunThread = true; 
    boolean ServerOn = true; 
    int gotPortNumber = 0; 
    public ClientReceive(Socket s) throws FileNotFoundException 
    { 
     //super(); 
     clientSocket = s; 
    } 
    public void run() 
    { 
     while(true) 
     { 
      try 
      { 
        BufferedReader readFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
        String fromServer = readFromServer.readLine(); 
        if(fromServer.contains("filenameistotheright->` ") == true) 
        { 
         String[] parts = fromServer.split(" "); 
         String nonsense = parts[0]; 
         String filename = parts[1]; 
         System.out.println("Requested filename is: " + filename); 


         //sending file 

         FileInputStream fis = null; 
         BufferedInputStream bis = null; 
         OutputStream os = null; 

         File myFile = new File(filename); 
         byte [] mybytearray = new byte [(int)myFile.length()]; 
         fis = new FileInputStream(myFile); 
         bis = new BufferedInputStream(fis); 
         bis.read(mybytearray,0,mybytearray.length); 
         os = clientSocket.getOutputStream(); 
         System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)"); 
         os.write(mybytearray,0,mybytearray.length); 
         os.flush(); 

        } 
        else 
        { 
         String a = fromServer; 
         int i; 
         for(i = 0; i < a.length(); i++) 
         { 
          char c = a.charAt(i); 
          if('0' <= c && c <= '9') 
          { 
            break; 
          } 
         } 
         String alphaPart = a.substring(0, i); 
         String numberPart = a.substring(i); 
         System.out.println("Recieved from server: " + alphaPart +"\n"); 


         if(fromServer.equals(null)) 
         { 
          System.exit(0); 
         } 

        } 
        if(fromServer.equals(null)) 
        { 
        System.exit(0); 
        } 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      finally 
      { 

      } 
     } 
    } 
} 

TL上でそれを送信するコードです; DR:あなたが解決策を知っている場合この行では、以下のコードを読み、下にスクロールして答えます。合計で8つのクラスがあります。

メイン関数ファイル:

import java.io.*; 

public class Main 
{ 
    public static void main(String[] args) throws IOException, FileNotFoundException 
    { 

     Client client1 = null; 
     Server server1 = null; 

      for (int i = 0; i < args.length; i++) 
      { 

       if (args.length > 2) 
       { 
       client1 = new Client(args); 
       client1.clientRun2(args); 
       } 
       else if (args.length == 2) 
       { 
        server1 = new Server(args); 
        server1.serverRun2(args); 
       } 
      i=args.length + 20; 
      } 
    } 

} 

Serverファイル:

import java.io.*; 
import java.net.*; 
import java.util.*; 
import javax.imageio.IIOException; 
public class Server 
{ 
    private String[] serverArgs; 
    public Socket socket; 
    public Socket fileSocket; 
    public boolean keepRunning = true; 
    public int ConnectOnce = 0; 
    public String option = ""; 
    public boolean isConnected = false; 

    public Server(String[] args) throws IOException 
    { 
     // set the instance variable 

     this.serverArgs = args; 
     if(ConnectOnce == 0) 
     { 
      int port_number1 = Integer.valueOf(serverArgs[1]); 
      ServerSocket serverSocket = new ServerSocket(port_number1); 
      socket = serverSocket.accept(); 
      ConnectOnce = 4; 
      isConnected = true; 

     } 

    } 
    public String[] serverRun2(String[] args) throws IOException 
    { 

     serverArgs = args; 
     serverArgs = Arrays.copyOf(args, args.length); 
     serverSend.start(); 
     return serverArgs; 
    } 

    Thread serverSend = new Thread() 
    { 
     public void run() 
     { 
      OutputOptions(); 
      while(isConnected) 
      { 
       try 
       { 
        ServerRecieve serverThread = new ServerRecieve(socket); 
        serverThread.start(); 

        // input the message from standard input 
        BufferedReader input2= new BufferedReader(new InputStreamReader(System.in)); 

        option = input2.readLine(); 
        if(option.equals("m") || option.equals("M")) 
        { 
         StandardOutput(); 
        } 
        if(option.equals("f") || option.equals("F")) 
        { 
         SendFileName(); 
        } 
        if(option.equals("x") || option.equals("X")) 
        { 
         System.exit(0); 
        } 

       } 
       catch (Exception e) 
       { 
        System.out.println(e.getMessage()); 
       } 
      } 
     } 
    }; 


public void StandardOutput() 
{ 
     try 
     {   
      //Send the message to the client 
      OutputStream os = socket.getOutputStream(); 
      OutputStreamWriter osw = new OutputStreamWriter(os); 
      BufferedWriter bw = new BufferedWriter(osw); 

      //creating message to send from standard input 
      String newmessage = ""; 
      try 
      { 
       System.out.println("Enter your message: "); 
       // input the message from standard input 
       BufferedReader input2= new BufferedReader(new InputStreamReader(System.in)); 
       String line = ""; 

       line= input2.readLine(); 
       newmessage += line + " "; 

      } 
      catch (Exception e) 
      { 
       System.out.println(e.getMessage()); 
      } 
      String sendMessage = newmessage; 
      bw.write(sendMessage + "\n"); 
      bw.newLine(); 
      bw.flush(); 
      System.out.println("Message sent to client: "+sendMessage); 
      StandardInput(); 
      //run(); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      finally 
      { 

      } 

} 
public void SendFileName() throws FileNotFoundException 
{ 
    try 
    { 

      //Send the message to the client 
      OutputStream os = socket.getOutputStream(); 
      OutputStreamWriter osw = new OutputStreamWriter(os); 
      BufferedWriter bw = new BufferedWriter(osw); 

      //creating message to send from standard input 
      String newmessage = ""; 

      // input the message from standard input 
      BufferedReader input= new BufferedReader(new InputStreamReader(System.in)); 
      String line = ""; 
      System.out.println("What file do you want?"); 
      line= input.readLine(); 
      newmessage += line + " "; 
      String filename = newmessage; 
      bw.write("filenameistotheright->` " + filename); 
      bw.newLine(); 
      bw.flush(); 


      int maxsize = 9999; 
      int bytesRead; 
      int current = 0; 
      FileOutputStream fos = null; 
      BufferedOutputStream bos = null; 
      Socket sock = null; 

      // receive file 
      byte [] mybytearray = new byte [maxsize]; 
      InputStream is = sock.getInputStream(); 
      fos = new FileOutputStream(filename); 
      bos = new BufferedOutputStream(fos); 
      bytesRead = is.read(mybytearray,0,mybytearray.length); 
      current = bytesRead; 

      while(bytesRead > -1) 
      { 
        bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); 
        if(bytesRead >= 0) 
        { 
         current += bytesRead; 
        } 
      } 

      bos.write(mybytearray, 0 , current); 
      bos.flush(); 
      System.out.println("File " + filename + " downloaded (" + current + " bytes read)"); 
      StandardInput(); 
      // runClientRead(clientArgs); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
} 
void FileTransferSend() 
{ 
    //connect to the filetransfer 



    try 
    { 
     System.out.println("Which file do you want? "); 
     Scanner scanner = new Scanner(System.in); 
     String filename = scanner.nextLine(); 
     FileInputStream fis = new FileInputStream(new File(filename)); 
     DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fileSocket.getOutputStream())); 
     int element; 
     while((element = fis.read()) !=1) 
     { 
      dos.write(element); 
     } 
     byte[] byteBuffer = new byte[1024]; // buffer 

     while(fis.read(byteBuffer)!= -1) 
     { 
      dos.write(byteBuffer); 
     } 
     OutputOptions(); 


     // dos.close(); 
     // fis.close(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 

    } 
} 

void OutputOptions() 
{ 
    System.out.println("Enter an option ('m', 'f', 'x'): "); 
    System.out.println("(M)essage (send)"); 
    System.out.println("(F)ile (request) "); 
    System.out.println("e(X)it "); 
} 


public void StandardInput() 
{ 
    OutputOptions(); 
    while(true) 
    { 

     try 
     { 
      // input the message from standard input 
      BufferedReader input2= new BufferedReader(new InputStreamReader(System.in)); 
      String line2 = ""; 

      option= input2.readLine(); 
      if(option.equals("m") || option.equals("M")) 
      { 
       StandardOutput(); 
      } 
      if(option.equals("f") || option.equals("F")) 
      { 
       SendFileName(); 

      } 
      if(option.equals("x") || option.equals("X")) 
      { 
       System.exit(0); 

      } 

     } 
     catch (Exception e) 
     { 
      System.out.println(e.getMessage()); 
     } 
     finally 
     { 

     } 
    } 

} 




} 

サーバーRecievingスレッド1:

import java.net.ServerSocket; 
import java.net.Socket; 
import java.io.*; 

public class ServerRecieve extends Thread 
{ 
    int filePortNumber = 0; 
    Socket servSocket; 
    Socket fileSocket; 
    boolean m_bRunThread = true; 
    boolean ServerOn = true; 
    int gotPortNumber = 0; 
    int once = 0; 
    String fileNameGlobal = ""; 

    public ServerRecieve(Socket s) throws FileNotFoundException 
    { 
     super(); 
     this.servSocket = s; 
    } 
    public void run() 
    { 
     while(true) 
     { 
      try 
      { 
       BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream())); 
       String fromClient = readFromClient.readLine(); 

       if(fromClient.contains("filenameistotheright->` ") == true) 
       { 
        String[] parts = fromClient.split(" "); 
        final String filename = parts[1]; 
        System.out.println("Requested filename is: " + filename); 
        fileNameGlobal = filename; 
        //Sending the file 
        FileInputStream fis = null; 
        BufferedInputStream bis = null; 
        OutputStream os = null; 

        File myFile = new File(filename); 
        byte [] mybytearray = new byte [(int)myFile.length()]; 
        fis = new FileInputStream(myFile); 
        bis = new BufferedInputStream(fis); 
        bis.read(mybytearray,0,mybytearray.length); 
        os = servSocket.getOutputStream(); 
        System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)"); 
        os.write(mybytearray,0,mybytearray.length); 
        os.flush(); 

       } 
       else 
       { 
        String a = fromClient; 
        int i; 
        for(i = 0; i < a.length(); i++) 
        { 
         char c = a.charAt(i); 
         if('0' <= c && c <= '9') 
         { 
           break; 
         } 
        } 
        String alphaPart = a.substring(0, i); 
        String numberPart = a.substring(i); 
        System.out.println("Recieved from client: " + alphaPart +"\n"); 
        if(gotPortNumber == 0) 
        { 
         String[] parts1 = fromClient.split(" "); 
         String nonsense1 = parts1[0]; 
         String filename1 = parts1[1]; 
         System.out.println("File transfer port found: " + numberPart + "\n"); 
         gotPortNumber = 3; 
         filePortNumber = Integer.parseInt(numberPart); 
         int p = 0; 
         p = strToInt(numberPart); 

         System.out.println(filename1); 
         //starting the recieving thread 

         if(once == 0) 
         { 
          String[] parts12 = fromClient.split(" "); 
          String nonsense12 = parts12[0]; 
          String filename31 = parts12[1]; 
          //System.out.println("name:" + filename31); 
          String address = "localhost"; 
         // fileSocket = new Socket(address, p); 
          //ServerSocket serverSocket1 = new ServerSocket(p); 
          if((filename31.equals(null) == true) && (!filename31.equals("")==true)) 
          { 
           ServerFile getServerFile = new ServerFile(servSocket, p, filename31); 
           getServerFile.start(); 
          } 

          once = 4; 
         } 
         once = 4; 
        } 
        gotPortNumber = 3; 


        if(fromClient.equals(null)) 
        { 
         System.exit(0); 
        } 
        OutputOptions(); 
       } 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      finally 
      { 

      } 
     } 
    } 

    void OutputOptions() 
    { 
     System.out.println("Enter an option ('m', 'f', 'x'): "); 
     System.out.println("(M)essage (send)"); 
     System.out.println("(F)ile (request) "); 
     System.out.println("e(X)it "); 
    } 
    public int strToInt(String str) 
    { 
     int i = 0; 
     int num = 0; 
     boolean isNeg = false; 

     //Check for negative sign; if it's there, set the isNeg flag 
     if (str.charAt(0) == '-') { 
      isNeg = true; 
      i = 1; 
     } 

     //Process each character of the string; 
     while(i < str.length()) { 
      num *= 10; 
      num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++). 
     } 

     if (isNeg) 
      num = -num; 
     return num; 
    } 
} 

サーバーRecievingスレッド2:フルコンテキストで

import java.net.Socket; 
import java.io.*; 
import java.util.*; 
public class ServerFile extends Thread 
{ 
    public Socket servingSocket = null; 
    public int FilePort = 0; 
    public String otherName = ""; 
    public ServerFile(Socket ok, int port, String FileName) throws FileNotFoundException 
    { 
      this.FilePort = port; 
      this.servingSocket = ok; 
      this.otherName = FileName; 
    } 
    public void run() 
    { 
     while(true) 
     { 

      try 
      { 
       int maxsize = 999999; 
       byte[] buffer = new byte[maxsize]; 
       //servingSocket = new Socket("localhost", FilePort); 
       InputStream is = servingSocket.getInputStream(); 
       File test = new File(otherName); 
       test.createNewFile(); 
       FileOutputStream fos = new FileOutputStream(test); 
       BufferedOutputStream out = new BufferedOutputStream(fos); 
       int byteread = is.read(buffer, 0, buffer.length); 
       int current = byteread; 
       buffer = new byte[16384]; 

       while ((byteread = is.read(buffer, 0, buffer.length)) != -1) 
       { 
        out.write(buffer, 0, byteread); 
       } 
       out.flush(); 

        //socket.close(); 
        // fos.close(); 
        // is.close(); 


      } catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      finally 
      { 

      } 

     } 
    }  
} 

クライアントコード: https://www.dropbox.com/s/x2pjlw2wcgn8lhd/newcode.zip?dl=0

+0

ここには多すぎる問題があります。それをすべて投げ捨て、重複した質問に対する私の答えにコードを使用してください。 – EJP

答えて

1

あなたは例外があります。

あなたのサーバーファイルにはポケモンキャッチ(catch (Exception e)が「すべてをキャッチ」しています)があります。そのポケモンキャッチはスタックトレースではなく、例外メッセージを出力します。例外のメッセージはnullでもかまいません。それはあなたが見るnullです。

ここで、そのヌルはいつですか?さて、あなたは持っている:

Socket sock = null; 

// receive file 
byte [] mybytearray = new byte [maxsize]; 
InputStream is = sock.getInputStream(); 

socknullある場合さて、あなたはsock.getInputStream()を取得することはできません。あなたはNullPointerExceptionを取得します。それはあなたのキャッチオールにキャッチされ、おそらくメッセージがありません。

  • ポケモンキャッチを避けてください。
  • メッセージではなく、スタックトレースを必ず印刷してください。
  • sockに実際の値を指定してください。
+0

ありがとう、私はこれを試してみます。 – hey

関連する問題

 関連する問題