2014-04-17 72 views
4

我正在研究Spark流式處理實時數據,並且我構建了火花流式傳輸的例子wordCount,並且我可以運行以下示例: /bin/run-例子org.apache.spark.streaming.examples.JavaNetworkWordCount local [2] localhost 9999Spark:爲什麼流式傳輸不能連接java套接字客戶端

我在另一個終端上運行「nc -L -p 9999」,然後我可以在這個終端上鍵入字母,這個例子可以收到信件並給出正確的結果。

但是我開發了一個java socket客戶端發送內容到9999端口,爲什麼不能接收它的例子?我認爲這個例子只是監視9999端口,並從端口接收任何東西。

以下是Java部分:

File file = new File("D:\\OutputJson.dat"); 
    long l = file.length(); 
    socket = new Socket(); 
    boolean connected = false; 
    while (!connected) { 
     //not stop until send successful 
     try { 
      socket.connect(new InetSocketAddress("localhost", 9999)); 
      connected = true; 
      System.out.println("connected success!"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println("connected failed!"); 
      Thread.sleep(5000); 
     } 
    } 
    dos = new DataOutputStream(socket.getOutputStream()); 
    fis = new FileInputStream(file); 
    sendBytes = new byte[1024]; 
    while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { 
     sumL += length; 
     System.out.println("sent:" + ((sumL/l) * 100) + "%"); 
     dos.write(sendBytes, 0, length); 
     dos.flush(); 
    } 
    if (sumL == l) { 
     bool = true; 
    } 

這個Java函數總是返回錯誤: java.net.SocketException異常:插座關閉

我已經開發了另一個Java類從這個發送接收數據套接字,它工作正常,爲什麼火花不能接收?

+1

JavaNetworkWordCount假定記錄由\ n分隔。如果你的OutputJson.data中的數據沒有被\ n隔開,那麼火花流接收器不會找到記錄的結尾,所以不能正確接收任何內容。 –

回答

-1

從內存我想我使用了一個ServerSocket。該代碼類似於:

public void sendMsg(String msg) throws IOException { 
    ServerSocket serverSocket = null; 
    Socket clientSocket = null; 
    try { 
     serverSocket = new ServerSocket(port); 
     clientSocket = serverSocket.accept(); 
     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
     out.write(msg); 
     out.flush(); 
     out.close(); 
    } finally { 
     try { 
      clientSocket.close(); 
      serverSocket.close(); 
     } finally { 
      clientSocket = null; 
      serverSocket = null; 
     } 
    } 
} 
+0

這個問題不能用這個方法來解決,因爲spark不能從執行者寫出來 – pcejrowski