2017-03-15 21 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。

所以,我认为你需要修复你的发送方法。