Java Socket:不传输数据

时间:2017-03-15 16:16:36

标签: java sockets remote-server

我是套接字编程的新手。我想从本地文件中读取数据并通过套接字将其发送到服务器。当使用相同的机器(客户端和服务器在一台计算机上)进行测试时,它可以工作。但是,如果我在远程计算机上测试服务器,我没有从客户端计算机获取数据。任何人都可以帮我查看我的代码吗?非常感谢!

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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在您的发送方法中,您不会从InputStream中读取任何数据。当您在其构造函数中调用此new FileInputStream(filePath)时,只会创建一个带有目标路径的新File()。要获取一些数据,您需要从InputStream读取它,之后您可以将它写入OutputStream。

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