I made a server that sends a text file to the client (Android) and I'm only getting the file when I'm getting connection timed out.
Why the "connection timed out" is happening in the first place? and also, it takes like 1 minute to the file to be received (1MB).
Server:
FileInputStream fis = new FileInputStream(
new File("123.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
byte[] mybytearray = new byte[8192];
OutputStream os;
try {
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Client:
InputStream in;
int Size = 0;
try {
Size = clientSocket.getReceiveBufferSize();
in = clientSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
byte[] buffer = new byte[Size];
int read;
while ((read = dis.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
Any idea how to fix this problem?
You don't close stream on the server side. So nobody knows that this is the end of stream and wait continues till time out. Add close() like this:
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read;
while ((read = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, read);
}
os.close();
Also, on client side you should expect zero input. Its is OK for slow connection. Only -1 means that connection is closed. Change code like this:
while ((read = dis.read(buffer)) > -1)
Related
This question already has answers here:
How do I send file name with file using sockets in Java? [duplicate]
(3 answers)
Closed 6 years ago.
I am able to send Files through socket and receive on other ends . Now i want to send even file name so that after receiving file and saving file from socket i can save the name of file. What to add in client to send filename and in server to receive filename thanks in advance to all
Client.java
try {
clientSocket = new Socket(targetIP, port);
os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
signalActivity("About to start handshake");
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(fileToSend);
BufferedInputStream bis = new BufferedInputStream(fis);
// long BytesToSend = fileToSend.length();
while(true)
{
int bytesRead = bis.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
//BytesToSend = BytesToSend - bytesRead;
os.write(buffer,0, bytesRead);
os.flush();
}
fis.close();
bis.close();
br.close();
isr.close();
is.close();
pw.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
catch(Exception e)
{
}
Server.java
try {
welcomeSocket = new ServerSocket(port);
while(true && serviceEnabled)
{
socket = welcomeSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String inputData = "";
// String savedAs = "WDFL_File_" + System.currentTimeMillis();
//save the original name and extention
File file = new File(saveLocation, savedAs);
byte[] buffer = new byte[4096];
int bytesRead;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while(true)
{
bytesRead = is.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
bos.write(buffer, 0, bytesRead);
bos.flush();
}
bos.close();
socket.close();
//Start writing to file
}
} catch (IOException e) {
}
catch(Exception e)
{
}
Your client should send the file name first. After that the contents of the file.
The server should read the file name first so the following content of the file can be saved under the same file name.
1.client is sending file succesfully to server
2.server receives file successfully
But
3. when server tries to send this file back to client ,after working on received file( sent by client) following error occurs :
socket:null
connection is closed
This is sending file method back to client
"server code: "
public void sendFileBack(String fileName)
throws UnknownHostException,FileNotFoundException, IOException {
Socket sock = new Socket("192.168.0.103", 13267);
String tmpName=fName.replace(".mcrl2", ".lps");
File myFile = new File("out" + "\\" +tmpName );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
//Sending file data to the server
os.write(mybytearray, 0, mybytearray.length);
os.flush();
console.append("\n\n Output file transfered successfully \n \n");
//Closing socket
sock.close();
}
This is receiving file method back from server
"client code:"
private void receiveFileBack() throws IOException {
int bytesRead;
int port;
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.print("accepted connection"+clientSocket);
InputStream in = clientSocket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.print(fileName+"..........");
File f =new File("serverOut\\"+fileName);
OutputStream output = new FileOutputStream("serverOut\\"+fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 &&
(bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
serverStatus.append("Reading file..\n");
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
// Closing the FileOutputStream handle
output.close();
output.flush();
}
}
i want to send the file size and one other integer, the tabelet serial number from and android tablet to a server running windows 7:
what is wrong with my client code and how to make the server accept the to different byte streams of data?
client code of android tablet
try {
byte[] bytes = new byte[(int) length];
fis = new FileInputStream(file2);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(socket.getOutputStream());
int count;
// convert integer to byte
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(1992);
byte[] preByte = baos.toByteArray();
// the first byte that sends the tablet serial number and the size of the next file it is going to send
bis.read(preByte);
// the next sent is the file itself which is a database file
while ((count = bis.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
fis.close();
bis.close();
fis = null;
bis = null;
socket.close();
server code that will receive the two files
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
System.out.println("streams are setup from new thread\n");
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
buffer = new byte[bufferSize];
while ((count = is.read(buffer)) > 0) {
bos.write(buffer, 0, count);
} // end while
bos.flush();
bos.close();
is.close();
try this
dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
dos.writeLong(length);
dos.writeInt(1992);
for (int b; (b = bis.read()) != -1;) {
dos.write(b);
}
...
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
long length = dis.readLong();
int serialNumber = dis.readInt();
... read bytes
It seems that you are reading into preByte array instead of writing it to the output stream:
bis.read(preByte);
You probably meant:
bos.write(preByte);
You don't need the ByteArrayOutputStream at all. Just wrap a DataOutputStream around the BufferedOutputStream, and do all the writes via the DataOutputStream.
I have a server client file transfer program which works fine in java .but i copied it and changed the file location d:/ to environm.....
The problem is the filesize is lesser than sending one, hence its shown as corrupted.. Any idea .
SERVER SIDE
public class Server
{
// create socket
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
while(true)
{
ServerSocket servsock = new ServerSocket(13000);
System.out.println("Main Waiting...");
Socket socket = servsock.accept();
System.out.println("Accepted connection : " + socket);
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
long filesize = new Long(in.readLong());
System.out.println("received Size:"+filesize);
// read file name
String fname=in.readUTF();
System.out.println("server : file name: "+fname);
String prefix=fname.substring(0,fname.lastIndexOf('.')).trim();
String suffix=fname.substring(fname.lastIndexOf('.'),fname.length()).trim();
String file = prefix + suffix;
System.out.println("received name:"+file);
File f=new File("F:/Users/achu/Desktop/"+ file);// changed this in android
f.createNewFile();
// receive file
byte [] mybytearray = new byte [(int)(filesize)];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
System.out.println("current"+current);
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(current<filesize && bytesRead >-1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
is.close();
socket.close();
servsock.close();
}
}
CLIENT SIDE
public class Client
{
Socket socket=new Socket("101.59.43.58",13000);
System.out.println("Connectedddd");
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
File file = new File("d:/my.pdf");
out.writeLong(file.length());
out.flush();
out.writeUTF(file.getName());
byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Send:"+mybytearray.length);
OutputStream ous = socket.getOutputStream();
System.out.println("Sending...");
ous.write(mybytearray,0,mybytearray.length);
ous.flush();
bis.close();
ous.close();
System.out.println("closing socket...");
socket.close();
}
My client can send Images normally to server, but when it comes to text files they arrive empty. Any ideas what am I doing wrong? I'd really appreciate help, because I have been trying to make this work for many days now. Thanks.
Here is the server code:
class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
and here is the client code:
public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.newLine();
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
You are prematurely closing BufferedReader on server side before reading all the data. This essentially closes the connection.
You should not use Reader or Writer for non-character streams like binary image data. And you should not mix BufferedReader with any other stream wrapper for the same stream since it may read as many data as it fills in buffer.