It has been days I am struggling with this problem. I want to create a local android server to let other devices download a file in LAN. So far i have created a socket server that writes a pdf file along with header on output stream, but it is not working. When url is hit on web browser almost 95% of the data is downloaded without any problem after that download fails, it shows network problem(In Google chrome).
Following is the code to create server:
class VideoStreamServer {
public void startServer() {
outFilePath = getActivity().getExternalFilesDir("/") + "/pdf.pdf";
outFile = new File(outFilePath);
Runnable videoStreamTask = new Runnable() {
@Override
public void run() {
try {
ServerSocket socket = new ServerSocket(port);
System.out.println("Waiting for client to connect.");
while (true) {
Socket client = socket.accept();
BufferedOutputStream os = new BufferedOutputStream(client.getOutputStream());
FileInputStream in = new FileInputStream(outFile);
BufferedInputStream inFromClient = new BufferedInputStream(client.getInputStream());
StringBuilder sb = new StringBuilder();
sb.append("HTTP/1.1 200 OK\r\n");
sb.append("Accept-Ranges: bytes\r\n");
sb.append("Connection: close\r\n");
sb.append("Content-Length: " + in.available() + "\r\n");
sb.append("Content-Disposition: attachment; filename=file.pdf\r\n");
sb.append("Content-Type: application/pdf \r\n");
sb.append("\r\n");
byte[] data = new byte[1024];
int length;
//inFromClient.read(data);
//System.out.println("request from client"+getStreamData(inFromClient));
System.out.println("Thread Started");
//System.setProperty("http.keepAlive", "false");
os.write(sb.toString().getBytes());
while ((length = in.read(data)) != -1) {
os.write(data, 0, length);
}
os.close();
client.close();
socket.close();
in.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread streamServer = new Thread(videoStreamTask);
streamServer.start();
}
}
Any help would be appreciated.
EDIT1
public String getStreamData(InputStream in) {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}