2017-03-15 34 views
-1

我是新來的套接字編程。我想從本地文件讀取數據並通過套接字將其發送到服務器。當使用同一臺計算機進行測試(客戶端和服務器在一臺計算機上)時,它可以工作但是,如果我在遠程機器上測試服務器,我沒有得到我應該從客戶端機器獲得的數據。任何人都可以幫我看看我的代碼嗎?非常感謝!Java Socket:數據未被傳輸

public class GreetingClient{ 
private Socket socket; 

public GreetingClient(String serverName, int port) throws UnknownHostException, IOException { 
    this(new Socket(serverName,port)); 
} 


public GreetingClient(Socket socket) { 
    this.socket = socket; 
} 
public static void main(String[] args) { 
    String hostname; 
    int port; 
    if (args.length == 2) { 
     hostname = args[0]; 
     port = Integer.parseInt(args[1]); 

    } else { 
     hostname = "localhost"; 
     port = 6066; 
    } 
    System.out.println("Connecting to " + hostname + " on port " + port); 
    String filePath ="C:/Users/Documents/file.xml"; 
    GreetingClient c; 
    try { 
     c = new GreetingClient(hostname, port); 
     c.send(filePath); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
public void send(String filePath) throws IOException { 
    InputStream inputStream = new FileInputStream(filePath); 
    IOUtils.copy(inputStream , this.socket.getOutputStream()); 
    this.socket.getOutputStream().flush(); 
    this.socket.shutdownOutput(); 
    System.out.println("Finish sending file to Server."); 
} 
} 




public class GreetingServer extends Thread { 
private ServerSocket serverSocket; 
public GreetingServer(int port) throws IOException { 
    serverSocket = new ServerSocket(port); 
} 
public void run() { 
    while (true) { 
     try { 
      System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); 
      Socket server = serverSocket.accept(); 

      System.out.println("Just connected to " + server.getRemoteSocketAddress()); 
      if (!server.isClosed()) { 
       DataOutputStream out = new DataOutputStream(server.getOutputStream()); 
       out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\n Goodbye!"); 
      } 
      DataInputStream in = new DataInputStream(server.getInputStream()); 
      if (in != null) { 
       Upload upload = parseXmlToJaxb(in); 
       long clientID = upload.getClientID(); 
       System.out.println("Client "+clientID); 


       server.close(); 
      } else { 
       System.out.println("Unknown Message Received at " + _dateTimeFormatter.format(new Date())); 
      } 
     } catch (SocketTimeoutException s) { 
      System.out.println("Socket timed out!"); 
      break; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      break; 
     } 
    } 
} 
+0

*我沒有得到我應該*的數據。 - 以什麼方式?錯誤的數據?沒有數據?數據損壞? –

+0

我會去掉很多代碼,直到你剛剛離開客戶端和服務器,客戶端只是發送一個簡單的字節到服務器,並看看是否可行。然後慢慢重新添加其他代碼。 –

回答

0

在你的send方法中,你沒有從InputStream中讀取任何數據。當你在構造函數中調用new FileInputStream(filePath)時,只會創建一個帶有目標路徑的新File()。爲了獲得一些數據,你需要從InputStream中讀取數據,然後你可以將它寫入OutputStream。

所以,我認爲你需要修復你的發送方法。