Converting java.net.Socket.getInputStream() to byte[] showing large delay - java

I have designed a Java Client class that is required to send a byte[] array to a Java Server class via a socket. Here is my code:
ByteArrayClient.java
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ByteArrayClient {
public static void main(String[] args) {
//make POJO__________________________
ByteEncodeSubscriptionReq sr1=ByteEncodeSubscriptionReq.makeRequest(103, "Str1", "Str2");
//Connection details____________________
String serverName = "localhost";
int port = 6060;
try {
//Establish Connection with server_______________________________
System.out.println("ByteArrayClient: Connecting to " + serverName +":" + port+"...");
Socket client = new Socket(serverName, port);//make new socket
System.out.println("ByteArrayClient: connected to " + client.getRemoteSocketAddress());
//Encode POJO to ByteArray________________________________
byte[] SubscripReqByteArray=ByteEncodeSubscriptionReq.encode(sr1);
//encoded correctly to a 44 bit byte array
System.out.println("ByteArrayClient: SubscripTionRequest successfully encoded");
//Send POJO ByteArray to server__________________________
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;
System.out.println("ByteArrayClient: POJO sent to server");
//Receive Server response_________________________________
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("ByteArrayClient received: " + in.readUTF());
//close socket____________________________________
client.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("PojoClient: Connection Failed");
}
}
}
...and ByteArrayServer.java
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class ByteArrayServer extends Thread{
private ServerSocket serverSocket;
public ByteArrayServer(int port) throws IOException {
serverSocket = new ServerSocket(port);//create server socket
serverSocket.setSoTimeout(15000);//socket closes after 15 seconds
this.start();
}
public void run() {
while (true) {//server runs infinitely______________
try {
System.out.println("ByteArrayServer: Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket servedClient = serverSocket.accept();//client socket
System.out.println("ByteArrayServer: connected to " + servedClient.getRemoteSocketAddress());
//Receive Client ByteArray___________________________________________
ByteEncodeSubscriptionReq receivedReq=new ByteEncodeSubscriptionReq();//server side POJO
System.out.println("ByteArrayServer: created SubscriptionReq Object");
InputStream PojoStreamHolder = servedClient.getInputStream();
System.out.println("ByteArrayServer: client InputStream received");
byte[] clientByteStream=new byte[44];//same size as Pojo byte requirement
_____/*MY CODE IS STUCK SOMEWHERE HERE*/__________
servedClient.getInputStream().read(clientByteStream);
System.out.println("ByteArrayServer: clientByteStream received: "+clientByteStream[0]+" "+clientByteStream[1]);
receivedReq=ByteEncodeSubscriptionReq.decode(clientByteStream);
//Send confirmation to Client__________________________________________________
DataOutputStream out = new DataOutputStream(servedClient.getOutputStream());
if(receivedReq.getRequestSymbol().trim().length()!=0){
out.writeUTF("ByteArrayServer received Subscription ID="+receivedReq.getSubscriptionID());
System.out.println("ByteArrayServer: new SubscriptionRequest ID="+receivedReq.getSubscriptionID()+" Subscriber_Name="+receivedReq.getSubscriberName());
}else{
out.writeUTF("ByteArrayServer: did not receive Subscription ID");
}
//Close Client socket_________________________________________________________
//server.close();
//serverSocket.close();
} catch (SocketTimeoutException s) {
System.out.println("PojoServer: Socket timed out after " + getTimeElapsedInSeconds(startTime) + " seconds from start");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
// int port = Integer.parseInt(args[0]);//to get port as an Argument
int port = 6060;
try {
Thread t = new ByteArrayServer(port);
startTime = System.currentTimeMillis();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the Server console output:
ByteArrayServer: Waiting for client on port 6060...
ByteArrayServer: connected to /127.0.0.1:64233
ByteArrayServer: created SubscriptionReq Object
ByteArrayServer: client InputStream received
The issue is that while the Stream is received by the server without errors, it gets stuck near servedClient.getInputStream().read(clientByteStream); method and does not proceed further.
I've also tried
int count=servedClient.getInputStream().read(clientByteStream);
and
DataInputStream in = new DataInputStream(servedClient.getInputStream());
long bStr=in.readLong();
and
ObjectInputStream PojoObjHolder = new ObjectInputStream(PojoStreamHolder);
byte[] clientByteStream2 = (byte[])PojoObjHolder.readObject();
..but they show the same problem as well.
How should I pass the Byte Array between the two classes without extra imports?

The problem was in my ByteArrayClient Class. I had to link the OutputStream with the client socket, rather than creating a new instance of it. So I replaced:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;
with
OutputStream os = client.getOutputStream(out);
os.write(SubscripReqByteArray);;
Thank you for the hint Ekant

DataInputStream.readFully(byte[] b) will finish only when in inputstream bytes till b.length available. So for sure you need to debug if you have all the bytes or not.And the solution is to make those byte available so that the function will finish.
Same for DataInputStream.read(byte[] b) The method is blocked until input data is available.
Please make sure by debugging your app that inputstream have 44 bytes.
Try below to count available bytes and you can read those easily.
// count the available bytes form the input stream
int count = is.available();
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);

Related

Java network client sends only one message

I am learning Java and I'm writing an example client - server application.
The sokcket connection is fine, everything works well until the second message from the client app. It does not reach the server. If I start another client it also succeed at the first message, and fails at the second.
Anyone has an idea? Thanks in advance!
Server code:
package networking;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while (true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
String returnMessage = incomingMessage;
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
bw.flush();
System.out.println("))) " + returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
}
}
}
}
And the client
package networking;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = "";
/*
while(!message.equals("q")) {
System.out.print("Message: ");
message = console.readLine();
bw.write(message + "\n");
bw.flush();
System.out.println("))) " + message);
//Get the return message from the server
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
}
*/
for (int i = 0; i < 10; i++) {
bw.write(i + "\n");
bw.flush();
System.out.println("))) " + i);
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
}
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Your while is misplaced in your server code, and in fact you need 2 while loops:
one for accepting new clients
one for manage several messages by client
In pseudo code it gives you:
while (true):
accept new client
while (client connected):
read message from client
write back message to client
close client socket
If you want to use threads, then it's the inner while loop task which you have to delegate to a new thread.
Note: accept is blocking until a new client comes. That why you could send only one message by client.
Your server is not set up to handle this. You are reading one line, then discarding the connection for the GC, without closing it. The server, reading one line, then ignores all other lines and starts listening for the next connection.
Also, consider using threads.

Java seekable video stream

I'm trying made a simple video stream with Java.I got that play some mp4 video,but not all. On the other hand, I can't seek the stream when the video is playing(Tried in VLC and Chrome). I like to know: What problems does my code have?
Here is the code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
Thanks in advance

Sorting program using socket programming in java

I want to implement any one sorting algorithm using TCP/UDP on Server application and Give Input On Client side and client should sorted output from server and display sorted on input side. Here, I have created program for multiplication of a number. I am not getting how to pass int array from client side and receive the same array. How can I do that.It would be a great help. Thank in advance.
Client.java
package sorting_app;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
BufferedReader and BufferedWriter are for character streams.
Consider using other ways, like ObjectInputStream and ObjectOutputStream.
(DataOutputStream / DataInputStream could be good too)

Android app to server Socket program not reading String from app

I have an android app which will send a string to a server using the following code:
package com.example.testapp;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.1.125";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
In server side I am running a java program like the follows:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 5000;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
But it is not reading the String which I send from the android app. Instead when I submit from app, the java program shows the following errors:
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 54657374
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:803)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at SocketServerExample.main(SocketServerExample.java:29)
How can I fix this. Where is my error lays?? Is it on Server side or client side?? Please help me guys.
PROBLEM ANALYSIS:
You use a PrintWriter for sending from the client, but you use an ObjectInputStream on the receiving side of the server. These two are not compatible.
You have to use a pair of Writer and Reader together or a pair of ObjectOutputStream and ObjectInputStream, but you can't mix them.
SOLUTION:
We're going to use pairs of Writer and Reader. The client side already uses a Writer and a Reader, so we only need to change the server side.
On the server side, instead of the ObjectInputStream, use a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.readLine();
Moreover, use a PrintWriter instead of the ObjectOutputStream on the server side for sending back to the client:
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
writer.println(str);
Alltogether, then the server side looks like this:
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 5000;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
// //read from socket to ObjectInputStream object
// ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// //convert ObjectInputStream object to String
// String message = (String) ois.readObject();
// System.out.println("Message Received: " + message);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
System.out.println("Message Received: " + message);
// //create ObjectOutputStream object
// ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// //write object to Socket
// oos.writeObject("Hi Client "+message);
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
writer.println("Hi Client "+message);
//close resources
reader.close();
writer.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Use this on the client:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Use this on the server:
BufferedReader is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = is.readLine();
Use flush() after sending anything.
out.println(str);
out.flush();

Java - Download a file through browser using a Socket

i was studying Java Socket and i tried to develop a Socket using port 80 to download a file from browser.
So, i run my main class (source below), it will open a Socket in any port i want to.
Then someone outside will access http://MY_IP:MY_PORT/download/FILE_NAME
I got this all working, however the filesize on client side is 0 bytes (for small files), and slightly lower size for bigger archives (original 600mb, download 540mb+-)
I really checked my code a lot of times, i couldn't find any error, i also changed from java libs to Apache-commons thinking it would help, but no success.
so maybe i think i got something wrong on Response headers.
Can you guys help me please?
Thanks in advance.
Class HTTPDownload:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
class HTTPDownloader {
Socket incoming = null;
ServerSocket server = null;
public HTTPDownloader(){
int port = 11000;
try{
server = new ServerSocket(port);
System.out.println("Creating SocketServer on Port " + port);
}catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Preparing to accept connections...");
while(true){
try{
incoming = server.accept();
System.out.println("connection!");
HTTPDownloaderThread thread1 = new HTTPDownloaderThread(incoming);
thread1.start();
}catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException{
new HTTPDownloader();
}
}
Class HTTPDownloadThread:
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Paths;
class HTTPDownloaderThread extends Thread {
private static final int BUFFER_SIZE = 4096;
private Socket socket;
private byte[] buf = new byte[BUFFER_SIZE];
private OutputStream out;
private InputStream is;
HTTPDownloaderThread(final Socket socket){
this.socket = socket;
}
public void run(){
int numberRead = 0;
try{
out = socket.getOutputStream();
is = socket.getInputStream();
numberRead = is.read(buf, 0, BUFFER_SIZE);
System.out.println("read " + numberRead);
if(numberRead<0)
return;
byte[] readBuf = new byte[numberRead];
System.arraycopy(buf, 0, readBuf, 0, numberRead);
String header = new String(readBuf);
System.out.println(header);
String fileName = header.split("\r\n")[0].split(" ")[1].substring(1);
System.out.println(socket.getInetAddress().getHostAddress()+" asked for file: "+fileName);
File f = new File("C:\\TestFolder\\"+fileName);
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(("Content-Length: "+f.length()+"\r\n").getBytes());
out.write("Content-Type: application/octet-stream\r\n".getBytes());
out.write(("Content-Disposition: attachment; filename=\""+fileName+"\"\r\n").getBytes());
out.write("\r\n".getBytes()); // Added as Joy RĂȘ proposed, make it work!
Files.copy(Paths.get("C:\\TestFolder\\"+fileName) , out);
System.out.println("File upload completed!");
// out.flush();
out.close();
socket.close();
}catch(SocketException e) {
System.out.println(e.getMessage());
}catch(Exception e){
e.printStackTrace();
}
}
}
For one thing, add another "\r\n" between headers and data. Check your HTTP Response; does the Content-Length header report the correct file size for the downloaded file? Do the files show up usable on the client in the same way they were on the server?
Web proxies always helpful in debugging HTTP (or other client-server) applications :)
Also, I'm assuming you are specifying port 11000 on the browser, as that's what you're listening on on the server
The website does not let me to comment but i thought that I should tell about my findings.. By using
Files.copy("path",outStreamObj);
outStreamObj.close();
socketObj.close();
Will cause incomplete or corrupt downloads but if still want to use then outStreamObj and socketObj must not be closed the files transfer is fast with the above code (atleast from my observation). If you try to close it will report Broken Pipe or Connection reset or will not complete the download(freeze it).
Instead using the following code will let you close the outStreamObj as socketObj but file download is slow from the socket probably because of while loop.
Socket socket=serverSocket.accept();
FileInputStream fs=new FileInputStream(path);
OutputStream out = socket.getOutputStream();
//This is the change from the Files.copy()
int reads=0;
while((reads=fs.read())!=-1)
{
out.write(reads);
}
out.close();
socket.close();

Categories