2012-11-11 41 views
0

這是一項任務。使用java套接字從客戶端發送文本文件到服務器

我在尋找一些建議,以便我在這裏出錯。我的目標是從文件中讀取文本,將其發送到服務器並將該文本寫入新文件。

問題是即時通訊不完全確定如何做到這一點,我看了很多例子,其中沒有太多的幫助。

按原樣解釋程序。用戶將被要求輸入一個與該代碼的if語句相關的代碼。我想要關注的是代碼200,它是服務器代碼的上傳文件。

當我運行代碼我有我得到下面的這個錯誤。有人可以向我解釋我哪裏會出錯,我會很感激。

Connection request made 
Enter Code: 100 = Login, 200 = Upload, 400 = Logout: 
200 
java.net.SocketException: Connection reset 
     at java.net.SocketInputStream.read(Unknown Source) 
     at java.net.SocketInputStream.read(Unknown Source) 
     at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) 
     at sun.nio.cs.StreamDecoder.implRead(Unknown Source) 
     at sun.nio.cs.StreamDecoder.read(Unknown Source) 
     at java.io.InputStreamReader.read(Unknown Source) 
     at java.io.BufferedReader.fill(Unknown Source) 
     at java.io.BufferedReader.readLine(Unknown Source) 
     at java.io.BufferedReader.readLine(Unknown Source) 
     at MyStreamSocket.receiveMessage(MyStreamSocket.java:50) 
     at EchoClientHelper2.getEcho(EchoClientHelper2.java:34) 
     at EchoClient2.main(EchoClient2.java:99) 

和服務器上此錯誤:

Waiting for a connection. 
connection accepted 
message received: 200 
java.net.SocketException: Socket is not connected 
     at java.net.Socket.getInputStream(Unknown Source) 
     at EchoServer2.main(EchoServer2.java:71) 

回答

3

MyStreamSocket類並不需要擴展插槽。神祕的錯誤信息是因爲由MyStreamSocket表示的Socket永遠不會連接到任何東西。其socket成員引用的套接字是連接的套接字。因此,當你從MyStreamSocket獲得輸入流時,它確實沒有連接。這會導致錯誤,這意味着客戶端關閉。這導致套接字關閉,服務器正確地報告

使用BufferedReader會導致您的問題。它總是讀取儘可能多的數據到緩衝區中,所以在文件傳輸開始時,它將讀取「200」消息,然後發送文件的前幾個Kb,它將被解析爲字符數據。結果將是一堆錯誤。

我建議你現在擺脫BufferedReader並改用DataInputStream和DataOutputStream。您可以使用writeUTF和readUTF方法發送您的文本命令。要發送文件,我會建議一個簡單的塊編碼。

這可能是最簡單的,如果我給你的代碼。

首先你的客戶類。

import java.io.*; 
import java.net.InetAddress; 

public class EchoClient2 { 

    public static void main(String[] args) { 
     InputStreamReader is = new InputStreamReader(System.in); 
     BufferedReader br = new BufferedReader(is); 

     File file = new File("C:\\MyFile.txt"); 

     try { 
      System.out.println("Welcome to the Echo client.\n" 
        + "What is the name of the server host?"); 
      String hostName = br.readLine(); 
      if(hostName.length() == 0) // if user did not enter a name 
       hostName = "localhost"; // use the default host name 
      System.out.println("What is the port number of the server host?"); 
      String portNum = br.readLine(); 
      if(portNum.length() == 0) portNum = "7"; // default port number 
      MyStreamSocket socket = new MyStreamSocket(
        InetAddress.getByName(hostName), Integer.parseInt(portNum)); 
      boolean done = false; 
      String echo; 
      while(!done) { 

       System.out.println("Enter Code: 100 = Login, 200 = Upload, 400 = Logout: "); 
       String message = br.readLine(); 
       boolean messageOK = false; 

       if(message.equals("100")) { 
        messageOK = true; 
        System.out.println("Enter T-Number: (Use Uppercase 'T')"); 
        String login = br.readLine(); 
        if(login.charAt(0) == 'T') { 
         System.out.println("Login Worked fantastically"); 
        } else { 
         System.out.println("Login Failed"); 
        } 
        socket.sendMessage("100"); 
       } 

       if(message.equals("200")) { 
        messageOK = true; 
        socket.sendMessage("200"); 
        socket.sendFile(file); 
       } 
       if((message.trim()).equals("400")) { 
        messageOK = true; 
        System.out.println("Logged Out"); 
        done = true; 
        socket.sendMessage("400"); 
        socket.close(); 
        break; 
       } 

       if(! messageOK) { 
        System.out.println("Invalid input"); 
        continue; 
       } 

       // get reply from server 
       echo = socket.receiveMessage(); 
       System.out.println(echo); 
      } // end while 
     } // end try 
     catch (Exception ex) { 
      ex.printStackTrace(); 
     } // end catch 
    } // end main 
} // end class 

那麼你的服務器類:

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

public class EchoServer2 { 
    static final String loginMessage = "Logged In"; 

    static final String logoutMessage = "Logged Out"; 


    public static void main(String[] args) { 
     int serverPort = 7; // default port 
     String message; 

     if(args.length == 1) serverPort = Integer.parseInt(args[0]); 
     try { 
      // instantiates a stream socket for accepting 
      // connections 
      ServerSocket myConnectionSocket = new ServerSocket(serverPort); 
      /**/System.out.println("Daytime server ready."); 
      while(true) { // forever loop 
       // wait to accept a connection 
       /**/System.out.println("Waiting for a connection."); 
       MyStreamSocket myDataSocket = new MyStreamSocket(
         myConnectionSocket.accept()); 
       /**/System.out.println("connection accepted"); 
       boolean done = false; 
       while(!done) { 
        message = myDataSocket.receiveMessage(); 

        /**/System.out.println("message received: " + message); 

        if((message.trim()).equals("400")) { 
         // Session over; close the data socket. 
         myDataSocket.sendMessage(logoutMessage); 
         myDataSocket.close(); 
         done = true; 
        } // end if 

        if((message.trim()).equals("100")) { 
         // Login 
         /**/myDataSocket.sendMessage(loginMessage); 
        } // end if 

        if((message.trim()).equals("200")) { 

         File outFile = new File("C:\\OutFileServer.txt"); 
         myDataSocket.receiveFile(outFile); 
         myDataSocket.sendMessage("File received "+outFile.length()+" bytes"); 
        } 

       } // end while !done 
      } // end while forever 
     } // end try 
     catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } // end main 
} // end class 

然後StreamSocket類:

public class MyStreamSocket { 
    private Socket socket; 

    private DataInputStream input; 

    private DataOutputStream output; 


    MyStreamSocket(InetAddress acceptorHost, int acceptorPort) 
      throws SocketException, IOException { 
     socket = new Socket(acceptorHost, acceptorPort); 
     setStreams(); 
    } 


    MyStreamSocket(Socket socket) throws IOException { 
     this.socket = socket; 
     setStreams(); 
    } 


    private void setStreams() throws IOException { 
     // get an input stream for reading from the data socket 
     input = new DataInputStream(socket.getInputStream()); 
     output = new DataOutputStream(socket.getOutputStream()); 
    } 


    public void sendMessage(String message) throws IOException { 
     output.writeUTF(message); 
     output.flush(); 
    } // end sendMessage 


    public String receiveMessage() throws IOException { 
     String message = input.readUTF(); 
     return message; 
    } // end receiveMessage 


    public void close() throws IOException { 
     socket.close(); 
    } 


    public void sendFile(File file) throws IOException { 
     FileInputStream fileIn = new FileInputStream(file); 
     byte[] buf = new byte[Short.MAX_VALUE]; 
     int bytesRead;   
     while((bytesRead = fileIn.read(buf)) != -1) { 
      output.writeShort(bytesRead); 
      output.write(buf,0,bytesRead); 
     } 
     output.writeShort(-1); 
     fileIn.close(); 
    } 



    public void receiveFile(File file) throws IOException { 
     FileOutputStream fileOut = new FileOutputStream(file); 
     byte[] buf = new byte[Short.MAX_VALUE]; 
     int bytesSent;   
     while((bytesSent = input.readShort()) != -1) { 
      input.readFully(buf,0,bytesSent); 
      fileOut.write(buf,0,bytesSent); 
     } 
     fileOut.close(); 
    }  
} // end class 

溝的 「助手」 類。它並沒有幫助你。

相關問題