2017-03-07 61 views
0

我一直在试图建立一个MJPEG服务器,并对于这一点,我有一个简单的基本服务器from here。大部分代码都是一样的,只是修改了handle(socket)函数。这里是handle(...)码 -无法建立的Java/Android上MJPEG服务器

private void handle(Socket socket) { 
    try { 
     ... 
     Read HTTP request... Not needed for MJPEG. 
     ... 
     // Initial header for M-JPEG. 
     String header = "HTTP/1.0 200 OK\r\n" + 
       "Connection: close\r\n" + 
       "Max-Age: 0\r\n" + 
       "Expires: 0\r\n" + 
       "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r\n" + 
       "Pragma: no-cache\r\n" + 
       "Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n\r\n"; 
     output.write(header.getBytes()); 

     // Start the loop for sending M-JPEGs 
     isStreaming = true; 
     if (!socket.isClosed()) { 
      new Thread(new Runnable() { 
       int id = 1; 
       @Override 
       public void run() { 
        try { 
         while (isStreaming) { 
          if (id > 2) id = 1; 
          byte[] buffer = loadContent(id + ".jpg"); 
          output.write(("--boundary\r\n" + 
            "Content-Type: image/jpeg\r\n" + 
            "Content-Length: " + buffer.length + "\r\n").getBytes()); 
          output.write(buffer); 
          Thread.sleep(1000); 
          Log.i("Web Server", "Current id: " + id); 
          id++; 
         } 
        } catch (IOException | InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      }).start(); 
     } 
     output.flush(); 
     output.close(); 
     reader.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

我从一些网站的标题,而这个服务器在C++/Linux下正常(我不能直接移植代码,因为在C++中,我用的Qt QTcpServer这是一个与SocketServer有点不同)。

里有资产的文件夹2个JPG文件,这台服务器的工作是向他们展示和改变两者的每一秒之间。

当我的笔记本电脑打开这个网站上的谷歌浏览器,我得到的只是一个白色的屏幕(当服务器连接发生,但不正确的输出数据)。

如果需要任何其他信息,请在评论中问他们,我会编辑的问题,并添加他们。

谢谢!

回答

0

实测值的溶液中。显然,使用线程内的线程不起作用。这是新代码 -

if (!socket.isClosed()) { 
    int id = 1 
    while (isStreaming) { 
     try { 
      if (id > 2) id = 1; 
      byte[] buffer = loadContent(id + ".jpg"); 
      assert buffer != null; 
      Log.i("Web Server", "Size of image: " + buffer.length + "bytes"); 

      output.write(("--boundary\r\n" + 
          "Content-Type: image/jpeg\r\n" + 
          "Content-Length: " + buffer.length + "\r\n\r\n").getBytes()); 
      output.write(buffer); 
      Thread.sleep(100); 
      Log.i("Web Server", "Current id: " + id); 
      id++; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
相关问题