TCPServer / TCP Client File transfer issue: 0 bytes - java

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();
}
}

Related

send multiple files to multiple computers in java

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!");
}
}
}

Time factor in Client server program to measure upload and download time of video file

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
}
}
}
}
}

How to resolve socket closed exception

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
}
}
}
}
}

Client-Server communication via Socket

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.

How to receive file from multiple clients?

I created a program which will send a file to the server or to clients
my problem is I have 2 clients and they both need to send a file to the server
what happens is that the server is able to receive the file only from 1 client(the one who sends the file first)
how can I resolve this problem?
here's my code:
SERVER
private void sendFile(File file)throws IOException
{
Socket socket = null;
String host = "127.0.0.1";
String receiver=txtReceiver.getSelectedItem().toString();
int port=0;
if(receiver=="Client1")
{
host="127.0.0.2";
port=4441;
}
else if(receiver=="Client2")
{
port=4442;
host="127.0.0.3";
}
else if(receiver=="Server")
{
port=4440;
host="127.0.0.1";
}
socket = new Socket(host, port);
//File file = new File("Client.txt");
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
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();
}
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4440);
} catch (IOException ex)
{
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
try
{
socket = serverSocket.accept();
} catch (IOException ex)
{
System.out.println("Can't accept client connection. ");
}
try
{
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
} catch (IOException ex)
{
System.out.println("Can't get socket input stream. ");
}
try
{
fos = new FileOutputStream("C:\\Users\\Jake_PC\\Documents\\NetBeansProjects\\OJT2\\ServerReceivables\\file.txt");
bos = new BufferedOutputStream(fos);
} catch (FileNotFoundException ex)
{
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0)
{
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
socket.close();
serverSocket.close();
CLIENT
public static void main(String args[])throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4441);
} catch (IOException ex)
{
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
try
{
socket = serverSocket.accept();
} catch (IOException ex)
{
System.out.println("Can't accept client connection. ");
}
try
{
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
} catch (IOException ex)
{
System.out.println("Can't get socket input stream. ");
}
//C:\Users\Jake_PC\Documents\NetBeansProjects\OJT2
try
{
fos = new FileOutputStream("C:\\Users\\Jake_PC\\Documents\\NetBeansProjects\\OJT2\\Client1Receivables\\file.txt");
bos = new BufferedOutputStream(fos);
} catch (FileNotFoundException ex)
{
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0)
{
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
socket.close();
serverSocket.close();
}
private void sendFile(File file)throws IOException
{
Socket socket = null;
String host = "127.0.0.1";
String receiver=txtReceiver.getSelectedItem().toString();
int port=0;
if(receiver=="Client1")
{
port=4441;
}
else if(receiver=="Client2")
{
port=4442;
}
else if(receiver=="Server")
{
port=4440;
}
socket = new Socket(host, port);
//File file = new File("Client.txt");
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
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 need to start a new thread to handle each accepted socket. Examples abound. See for example the Custom Networking trail in the Java Tutorial.

Categories

Resources