2017-03-07 40 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(); 
     } 
    } 
} 
相關問題