I am trying to make a local web server using socket that will stream a video.
Following is my code for server:
class VideoStreamServer {
public void startServer() {
outFile = new File(outFilePath);
Runnable videoStreamTask = new Runnable() {
@Override
public void run() {
try {
ServerSocket socket = new ServerSocket(port);
StringBuilder sb = new StringBuilder();
sb.append( "HTTP/1.1 200 OK
");
sb.append( "Content-Type: audio/mpeg
");
sb.append( "Connection: close
" );
sb.append( "Accept-Ranges: bytes
" );
sb.append( "Content-Length: " + outFile.length() + "
" );
sb.append( "
");
System.out.println("Waiting for client to connect.");
while (true) {
Socket client = socket.accept();
System.out.println("Thread Started");
BufferedOutputStream os = new BufferedOutputStream(client.getOutputStream());
FileInputStream in = new FileInputStream(outFile);
byte[] data = new byte[1024];
int length;
//System.setProperty("http.keepAlive", "false");
os.write(sb.toString().getBytes());
while ((length = in.read(data)) != -1){
os.write(data,0,length);
}
os.flush();
os.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread streamServer = new Thread(videoStreamTask);
streamServer.start();
}
}
So the problem is whenever I hit url in web browser following exception is thrown.
java.net.SocketException: sendto failed: EPIPE (Broken pipe)
at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:499)
at libcore.io.IoBridge.sendto(IoBridge.java:468)
at java.net.PlainSocketImpl.write(PlainSocketImpl.java:508)
at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:270)
at java.io.BufferedOutputStream.flushInternal(BufferedOutputStream.java:185)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:139)
at com.example.sachinchandil.myapplication.VideoStreamDownloaderFragment$VideoStreamServer$1.run(VideoStreamDownloaderFragment.java:285)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.ErrnoException: sendto failed: EPIPE (Broken pipe)
at libcore.io.Posix.sendtoBytes(Native Method)
at libcore.io.Posix.sendto(Posix.java:156)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:177)
at libcore.io.IoBridge.sendto(IoBridge.java:466)
... 7 more
And if i download this file using HttpUrlConnection
all bytes frame are download except last and same exception is thrown.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…