I need to transfer few files to different computers, 1 file per 1 computer. Now i can only transfer 1 file to 1 computer. Also some computers from my IP pool can be offline, how can i avoid Exception?
Also I have all code in github:
https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test
Client
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;
public static void main(String[] args) throws IOException {
public static void sendFile(File myFile) {
//connecting
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("1");
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
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();
System.out.println("File " + myFile.getName() + " sent to Server.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("2");
ps.println(fileName);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_" + 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) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
in.close();
System.out.println("File " + fileName + " received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package xym4uk.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket.getInetAddress());
Thread t = new Thread(new CLIENTConnection(clientSocket));
t.start();
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}
}
}
ClientConnection
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection;
while ((clientSelection = in.readLine()) != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
String outGoingFileName;
while ((outGoingFileName = in.readLine()) != null) {
sendFile(outGoingFileName);
}
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + 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) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File "+fileName+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
//handle file send over socket
OutputStream os = clientSocket.getOutputStream();
//Sending file name and file size to the client
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}
Related
I have completed client server program to download and upload a video(media) file, but I am unable to figure out how to calculate the upload, download time separately and make it run repeatedly to measure improvement in time? I will be running client at one IP and server at different IP.
Source code of the client;
package wdc;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket("127.0.0.1", 3248);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("C:\\file1.avi");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
And the source code of the server side;
package wds;
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File("C:\\file2.avi");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
I can transfer the files but when I want to open them it says that the file is corrupted (because its 0 bytes long). T
When I start the TCPServer it waits for clients and accepts them and then sends the file to them. The client recives the file (but not all of it I assume ?) When I tried this with a picture.png that is 10 kb it worked. With anything else, it does not. I also did port forwarding (else the client couldnt get the file)
THIS IS THE TCPSERVER:
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:/Users/Tim/Desktop/P&P/Background music for P&P/Rock.wav";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3222);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(
connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File(fileToSend);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
HERE IS THE TCP CLIENT:
import java.io.*;
import java.net.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
class TCPClient {
private final static String serverIP = "123.123.123.123";
private final static int serverPort = 3222;
private final static String fileOutput = "C:/Users/Daniel/Desktop/check.wav";
public static void main(String args[]) {
while (true) {
byte[] aByte = new byte[1024];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket(serverIP, serverPort);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(fileOutput);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
// Music is played here
try {
AudioInputStream input = AudioSystem
.getAudioInputStream(new File(fileOutput));
SourceDataLine line = AudioSystem.getSourceDataLine(input
.getFormat());
line.open(input.getFormat());
line.start();
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer, 0, 1024)) != -1) {
line.write(buffer, 0, count);
}
line.drain();
line.stop();
line.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Refactored your client code a little bit:
no need for the ByteArrayOutputStream when already using a BufferedOutputStream
use bytesRead for byte array offset
This worked for me:
if (is != null)
{
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try
{
fos = new FileOutputStream(new File(fileOutput));
bos = new BufferedOutputStream(fos);
while ((bytesRead = is.read(aByte)) != -1)
{
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
I wrote a client server program which does the following:
1.Client sends the file to server
2.Server reads the file does some changes and sends back a message to client
3.Client should read the message
In 3rd step I am getting this error
Client program
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private static final String serverIP = "127.0.0.1";
private static final int serverPort = 3248;
private static final String fileToSend = "content.txt";
public static void main(String args[]) throws InterruptedException, UnknownHostException, IOException {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
DataOutputStream outToServer = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
clientSocket = new Socket( serverIP , serverPort );
outToServer = new DataOutputStream(clientSocket.getOutputStream());
is=clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
if (outToServer != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToServer.write(mybytearray, 0, mybytearray.length);
outToServer.flush();
outToServer.close();
// File sent, exit the main method
} catch (IOException ex) {
// Do exception handling
}
}
if(is!=null){
try {
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
System.out.println("in ");
for(byte b:baos.toByteArray()){
System.out.print(b);
}
return;
} catch (IOException ex) {
// Do exception handling
System.out.println(""+ex.getMessage());
}
finally{
clientSocket.close();
is.close();
}
}
}
}
Server Program
import java.io.*;
import java.net.*;
class TCPServer {
private static final String fileOutput = "output.txt";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
FileInputStream fromClient=null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
fromClient=(FileInputStream)connectionSocket.getInputStream();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//System.out.println(""+fromClient);
if(fromClient !=null){
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = fromClient.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = fromClient.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
connectionSocket.close();
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
I am trying to send data from my Server to my Client via Socket communication and I am receiving an error at the receiving end.
Here are my code snippets-
Server- This class is called CLIENTConnection and takes care of all the connections from server to client
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection=in.readLine();
while (clientSelection != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
System.out.println("inside case 2");
String outGoingFileName = in.readLine();
System.out.println(outGoingFileName);
while (outGoingFileName != null) {
System.out.println("Inside while loop");
sendFile(outGoingFileName);
}
System.out.println("Out of while");
break;
case "3":
receiveFile();
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String filename = clientData.readUTF();
System.out.println(filename+" is received on server side");
OutputStream output = new FileOutputStream(("C://Users/Personal/workspace/ClientServer/src/dir/"+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) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File "+filename+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
File myFile = new File("C://Users/Personal/workspace/ClientServer/src/dir/"+fileName);
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);
//handle file send over socket
OutputStream os = clientSocket.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();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}
Client Side (Receive File)
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream os;
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream inFromServer;
try
{
sock = new Socket("localhost", 7777);
stdin = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
inFromServer= new ObjectInputStream(sock.getInputStream());
os = new PrintStream(sock.getOutputStream());
try {
switch (Integer.parseInt(selectAction())) {
case 1:
os.println("1");
sendFile();
break;
case 2:
os.println("2");
System.err.print("Enter file name: ");
fileName = stdin.readLine();
os.println(fileName);
receiveFile(fileName);
break;
case 3:
os.println("3");
Synchronise();
}
} catch (Exception e) {
System.err.println("not valid input");
}
sock.close();
}
private static void Synchronise()
{
HashMap<String, Calendar> ClientFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/Client/");//getting the filename and timestamp of all the files present in client folder.
/*System.out.println("Client File List : \n");
for(String s : ClientFileList.keySet())
System.out.println(s);*/
HashMap<String, Calendar> ServerFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/src/dir/");//(HashMap<String, Calendar>) inFromServer.readObject();
/*System.out.println("\nServer File List : \n");
for(String s : ClientFileList.keySet())
System.out.println(s);*/
System.out.println("File comparision output");
compareTimestamp(ClientFileList,ServerFileList);
}
private static void compareTimestamp(HashMap<String, Calendar> ClientFileList, HashMap<String, Calendar> serverFileList)
{
LinkedList<String> fileToUpload=new LinkedList<String>();
LinkedList<String> fileToDownload=new LinkedList<String>();
LinkedList<String> fileToDeleteFromClient=new LinkedList<String>();
LinkedList<String> fileToDeleteFromServer=new LinkedList<String>();
Calendar clientCalender = null,serverCalendar=null;
for (String filename : serverFileList.keySet())
{
serverCalendar=serverFileList.get(filename);
if(ClientFileList.containsKey(filename))
{
clientCalender=ClientFileList.get(filename);
if(clientCalender.before(serverCalendar))
{
fileToDownload.add(filename);
}
else
{
fileToUpload.add(filename);
}
}
else
{
fileToDeleteFromClient.add(filename);
}
}
for (String filename : ClientFileList.keySet())
{
clientCalender=ClientFileList.get(filename);
if(!serverFileList.containsKey(filename))
{
fileToDeleteFromServer.add(filename);
}
}
System.out.println("Files to download to client: "+fileToDownload);
System.out.println("Files to upload to Server: "+fileToUpload);
System.out.println("Files to delete from client: "+fileToDeleteFromClient);
System.out.println("Files to delete from Server: "+fileToDeleteFromServer);
sendFile(fileToDeleteFromServer);
}
private static HashMap<String, Calendar> getTimeStamp(String location)
{
HashMap<String,Calendar> fileList = new HashMap<String,Calendar>();
File dir = new File(location);
File[] files = dir.listFiles();
if (files.length == 0)
{
System.out.println("No file found");
//System.exit(1);
}
else
{
for (int i = 0; i < files.length; i++)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(files[i].lastModified());
fileList.put(files[i].getName(), calendar);
}
}
return fileList;
}
public static String selectAction() throws IOException
{
System.out.println("1. Send file.");
System.out.println("2. Recieve file.");
System.out.println("3. Synchronize");
System.out.print("\nMake selection: ");
return stdin.readLine();
}
public static void sendFile()
{
try {
System.err.print("Enter file name: ");
fileName = stdin.readLine();
File myFile = new File("C:/Users/Personal/workspace/ClientServer/Client/"+fileName);
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();
dis.close();
System.out.println("File "+fileName+" sent to Server.");
}
catch (Exception e)
{
System.err.println("File does not exist!");
}
}
//receive a list of file to upload to server from client.
static void sendFile(LinkedList<String> fileList)
{
for(String file: fileList)
sendFile(file);
}
public static void sendFile(String filename) {
File file = new File("C:/Users/Personal/workspace/ClientServer/Client/"+filename);
byte[] mybytearray = new byte[(int) file.length()];
FileInputStream fis;
try
{
fis = new FileInputStream(file);
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();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
dis.close();
System.out.println("File "+filename+" sent to Server.");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_"));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
in.close();
System.out.println("File "+fileName+" received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
It is showing me error at
filename = clientData.readUTF();
Please let me know if there are any possible solutions.
Are you getting the file?
public static void receiveFile(String fileName) {
boolean recieving = true; //new
while(recieving){ //new
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_"));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
in.close();
System.out.println("File "+fileName+" received from Server.");
} catch (EOFException e){ // new
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
recieving = false;
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
} //new
}
DataInputStreams use this exception to signal end of stream. So the exception in might not be an error, and just mean that the data has been sent.
Before reading you will have to check that you have actually received something, and then read it.
Check this:
This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.
I wrote some client - server program, that shares data but at server side i got EOFException after reciving data. I tried to fix it on my own but it is hard to find own errors.
The error is caused by this line: Message command =(Message) serInputStream.readObject();
Here is some output from server:
java.io.EOFException
at Java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at transfer.Serwerus.run(Serwerus.java:42)
Server code:
import java.io.*;
import java.net.*;
public class Serwerus implements Runnable
{
public InputStream is;
public FileOutputStream fos;
public BufferedOutputStream bos;
public ObjectOutputStream serOutputStream;
public ObjectInputStream serInputStream;
ServerSocket socket;
private String clientMessage, clientFileName;
private int clientFileSize;
public Serwerus()
{
try
{
socket = new ServerSocket(6060);
System.out.println("Server started....");
}
catch(IOException e)
{
System.err.println("Error: " + e);
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
Socket sock = socket.accept();
System.out.println("Client accepted");
serOutputStream = new ObjectOutputStream(sock.getOutputStream());
serInputStream = new ObjectInputStream(sock.getInputStream());
while (true)
{
Message command =(Message) serInputStream.readObject();
System.out.println("after readObject");
if (command.getCommand().startsWith("FileU"))
{
System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
serOutputStream.writeObject(new Message("Bring", "", 0));
//ReciveData(socket, command.getfileName(), command.getfileSize());
}
else if(command.getCommand().startsWith("Wait"))
{
System.out.println("hohoho");
ReciveData(sock, command.getfileName(), command.getfileSize());
}
else if(command.getCommand().startsWith("Quit"))
{
System.exit(1);
}
else
{
System.out.println("Unknow");
}
}
}
catch(ClassNotFoundException | IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
serInputStream.close();
serOutputStream.close();
socket.close();
}
catch (IOException e)
{
System.err.println("Fallen on closing socket.\n Error: " + e);
}
}
}
public void SendData(Socket sock, String filePath) throws Exception
{
File myFile = new File (filePath);
System.out.println("File name = " + myFile.getName() + " File len = " + (int)myFile.length());
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
System.out.println("Sending finished");
}
public void ReciveData(Socket sock, String filePath, int fileSize)
{
System.out.println("Recive in progress, filesize = " + fileSize);
int bytesRead = 0, current = 0;
byte[] array = new byte[fileSize];
try
{
is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
do
{
System.out.println(bytesRead);
bytesRead = is.read(array);
current += bytesRead;
}
while(bytesRead > -1);
bos.write(array, 0 , current);
bos.flush();
bos.close();
fos.close();
// sock.close();
System.out.println("Reciveing finished");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void main (String [] args ) throws IOException
{
new Thread(new Serwerus()).start();
}
}
Client code:
import java.io.*;
import java.net.*;
public class Clientus implements Runnable
{
InputStream is;
FileOutputStream fos;
BufferedOutputStream bos;
ObjectOutputStream cliOutputStream;
ObjectInputStream cliInputStream;
Socket socket;
File actFile;
private String serverMessage, serverFileName;
private int serverFileSize;
public Clientus()
{
try
{
socket = new Socket("localhost", 6060);
cliOutputStream = new ObjectOutputStream(socket.getOutputStream());
cliInputStream = new ObjectInputStream(socket.getInputStream());
File file = new File(<filepath>);
actFile = file;
}
catch (Exception e)
{
System.err.println("Error: " + e);
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
cliOutputStream.writeObject(new Message("FileU", actFile.getPath(), (int) actFile.length()));
cliOutputStream.flush();
//while (true)
//{
Message command =(Message) cliInputStream.readObject();
if (command.getCommand().startsWith("File"))
{
String name = command.getfileName();
int size = command.getfileSize();
System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
if(size != 0 && !"".equals(name))
{
//ReciveData(socket, 0);
}
}
else if(command.getCommand().startsWith("Bring"))
{
cliOutputStream.writeObject(new Message("Wait", "D:\\KP2\\Serwer\\dupa.txt",(int) actFile.length()));
cliOutputStream.flush();
try
{
SendData(socket, actFile.getPath());
//this.socket.close();
}
catch (Exception ex)
{
System.err.println("Error with: SendData()");
}
}
else if(command.getCommand().startsWith("Quit"))
{
System.exit(1);
}
else
{
System.out.println("Command unknown");
}
//}
}
catch(ClassNotFoundException | IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
socket.close();
cliOutputStream.close();
cliInputStream.close();
}
catch (IOException e)
{
System.err.println("Fallen on closing socket.\n Error: " + e);
}
}
}
public void SendData(Socket sock, String filePath) throws Exception
{
byte [] mybytearray = new byte [(int) new File(filePath).length()];
FileInputStream fis = new FileInputStream(filePath);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
fis.close();
bis.close();
os.close();
System.out.println("Sending finished");
}
public void ReciveData(Socket sock, String fileName, int fileSize)
{
int bytesRead, current = 0;
byte[] array = new byte[fileSize+1];
try
{
is = sock.getInputStream();
fos = new FileOutputStream(<file_path>);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(array,0,array.length);
current = bytesRead;
do
{
bytesRead = is.read(array, current, (array.length - current));
if(bytesRead >= 0)
current += bytesRead;
}
while(bytesRead > -1);
bos.write(array, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println("Send time: " + (end - start));
bos.close();
sock.close();
System.out.println("Reciveing finished");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void main (String [] args ) throws IOException
{
new Thread(new Clientus()).start();
}
}
Can anyone help?
Your client may be disconnected after sending data and because your server is waiting for more data, the EOFException will occurr.
To fix this problem, you can add try-catch block to catching this exception when the client disconnects.
You are using both the ObjectOutputStream and the socket's own OutputStream to send data on, and you are getting out of sync. When you send the raw data directly over the socket you aren't sending the length first, so the receiver doesn't know how many bytes belong to this transmission. In fact it just reads everything until EOS, so next time you call ObjectInputStream.readObject() it naturally gets an EOFException. To fix this:
Use the ObjectInputStream and ObjectOutputStream for everything.
Before sending the file, send its length, via writeLong().
At the receiver, when receiving the file, first get its length, via readLong(), then read exactly that many bytes from the ObjectInputStream and copy them to the file.