如何使用Java正确地从套接字流式传输数据

时间:2017-04-12 23:33:45

标签: java sockets csv tcp-ip

我正在尝试使用Java在套接字上传输数据,以尝试编写Kafka生产者。我写了一个类来提取数据,但我没有得到我期望的结果。我已经设置好了,所以数据是从Linux机器上流式传输的。数据源是一个csv文件,我正在使用nc实用程序进行流式处理。该类在Eclipse的Windows 10计算机上运行。当我上课时,我看到两件奇怪的事情。

  1. 列标题不会传输。
  2. 我只能上课一次。如果我想再次运行它,我必须停止nc并重新启动它。
  3. 以下是我的代码。我错过了什么吗?此时我只是尝试连接到套接字并将数据拉过来。

    我使用以下命令运行nc: $ nc -kl 9999< uber_data.csv

    以下是我的课程

    import java.net.*;
    import java.io.*;
    
    public class Client 
    {
    static String userInput;
    
    public static void main(String [] args)
    {
    
        try
        {
            InetAddress serverAddress = InetAddress.getByName("servername");
            Socket socket = new Socket(serverAddress, 9999);
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    
            while ((userInput = input.readLine()) != null) {
                System.out.println(input.readLine());
            }
    
            input.close();
            socket.close();
    
        }
        catch(UnknownHostException e1)
        {
            System.out.println("Unknown host exception " + e1.toString());
        }
        catch(IOException e2)
        {
            System.out.println("IOException " + e2.toString());
        }
        catch(IllegalArgumentException e3)
        {
            System.out.println("Illegal Argument Exception " + e3.toString());
        }
        catch(Exception e4)
        {
            System.out.println("Other exceptions " + e4.toString());
        }
    }
    }
    

3 个答案:

答案 0 :(得分:1)

首先,每个调用readLine()尝试从输入流中读取行。 在userInput = input.readLine()中,您读取标题,但println(input.readLine())读取正文并在控制台中打印。

while ((userInput = input.readLine()) != null) { 
     System.out.println(userInput); //instead input.readLine()
}

其次,我没有使用nc,但我认为如果你要在finally语句中关闭socket(和reader),问题就会解决。

答案 1 :(得分:1)

我希望它会有所帮助。

对于第一个问题:您试图打印userInput字符串。但它打印了另一个readline()电话的结果。

对于第二种情况:文件传输完毕后,您必须停止并重新启动nc;无论你做什么在你身边。它来自nc方面。

请参阅nc documentation

答案 2 :(得分:1)

你扔掉了每一个奇数线。它应该是:

while ((userInput = input.readLine()) != null) {
    System.out.println(userInput);
}

其次,你没有关闭套接字。使用try-with-resources:

try
{
    InetAddress serverAddress = InetAddress.getByName("servername");
    try (
        Socket socket = new Socket(serverAddress, 9999);
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    ) {
        while ((userInput = input.readLine()) != null) {
            System.out.println(input.readLine());
        }
    }
}
catch (...)