2017-08-15 130 views
0

我有一個應用程序,在本地網絡上通過套接字與其他設備進行通信。在那我也想轉移文件和文本。 我的問題是,我不知道如何獲取文件和文本,並在接收中管理它們!通過套接字發送和接收字符串和文件流

這是我的文字reciever:

try { 
      outputStream = new DataOutputStream(socket.getOutputStream()); 
      outputstream_external = outputStream; 
      inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      log("success to set streams"); 
     } 
     catch (IOException e1) { 
      log("Error: Connection is not stable, exit"); 
      shutdown(); 
     } 
     while (true) { 
      String message = null; 
      try { 
       message = inputStream.readLine(); 
       if (message == null) { 
        return; 
       } 
       G.log(message); 
       JSONObject object = new JSONObject(message); 
       String command = object.getString(Command.COMMAND); 
       G.log(message); 

這是我的文本發送:

public void sendCommand(String command) { 
     G.log("send command + " + command); 
     command = command.replace("\n", " ") + "\n"; 
     if (outputStream == null) { 
      return; 
     } 
     final String commend = command; 
     Thread thread = new Thread(new Runnable() { 

      @Override 
      public void run() { 
       // TODO Auto-generated method stub 
       try { 
        outputStream.write(commend.getBytes()); 
       } 
       catch (IOException e) { 
        e.printStackTrace(); 
        G.log("sendCommand into catch"); 
       } 
      } 
     }); 
     thread.start(); 

    } 

我怎麼能接收文字和文件一起?

回答

0

這就是爲什麼有這麼多的應用程序級別的網絡協議,如HTTP,FTP,SMTP。

就你而言,你需要兩種消息類型,一種是字符串,另一種是文件。每條消息應符合預定義的格式。例如,

[4個字節的消息類型] + [4個字節的消息長度] + [消息內容]

您構造上發送側消息,並且在接收器側解析消息。

但是,在大多數情況下,您不必重新發明輪子。在互聯網上搜索,找出是否有適合您的現有協議。

+0

Tnx,我如何構建這種格式的流並接收?你能給我解釋一下示例代碼嗎? –

+0

剛剛發現了幾個很好的教程,http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html和http://crunchify.com/java-nio-non-blocking-io-with-server -client-實例的Java-NIO-字節緩衝區和 - 信道選擇器的Java-NIO-VS-IO / – cmoaciopm