2017-08-15 129 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