how to send file via socket
how to send mp3,avi(large) files via socket. small files with size less than 100kb is possible but how to send large file..
- 4 Contributors
- 11 Replies
- 8K Views
- 14 Hours Discussion Span
- Latest Post 11 Years Ago Latest Post by NormR1
Recommended Answers Collapse Answers
What is the problem you are having with the large files?
Does the server dislike receiving too much data?
The basic mechanism is the same for any size file. Is the data arriving too fast for the client? In that case use the same socket connection to send ready/not ready messages from the client to the server to keep things synchronised.
Does the program work for some files and not for others?
Does the kind of file (text vs binary) make any difference?
All 11 Replies
What is the problem you are having with the large files?
Does the server dislike receiving too much data?
The basic mechanism is the same for any size file. Is the data arriving too fast for the client? In that case use the same socket connection to send ready/not ready messages from the client to the server to keep things synchronised.
import java.net.*; import java.io.*; public class FileClient< public static void main (String [] args ) throws IOException < int filesize=6022386; // filesize temporary hardcoded long start = System.currentTimeMillis(); int bytesRead; int current = 0; // localhost for testing Socket sock = new Socket("sathya-PC",13267); System.out.println("Connecting. "); // receive file byte [] mybytearray = new byte [filesize]; InputStream is = sock.getInputStream(); FileOutputStream fos = new FileOutputStream("abc.flv"); BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; // thanks to A. Cdiz for the bug fix do < bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); if(bytesRead >= 0) current += bytesRead; > while(bytesRead > -1); bos.write(mybytearray, 0 , current); bos.flush(); long end = System.currentTimeMillis(); System.out.println(end-start); bos.close(); sock.close(); > >
import java.net.*; import java.io.*; public class FileServer < public static void main (String [] args ) throws IOException < // create socket ServerSocket servsock = new ServerSocket(13267); while (true) < System.out.println("Waiting. "); Socket sock = servsock.accept(); System.out.println("Accepted connection : " + sock); // sendfile File myFile = new File ("java_test.flv"); 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(); >> >
Does the program work for some files and not for others?
Does the kind of file (text vs binary) make any difference?
I see you are reading the whole file into a buffer array before writing it. (Your use of a int for the file length limits you to 2GB anyway). It’s more normal to have a sensible sized buffer and use copy blocks from the file to the output stream until the file is consumed, eg
byte[] data = new byte[4096]; // 4k buffer, could be much larger int count; while ((count = file.read(data)) != -1)
Plus its a bad idea to hide exceptions — better to put your code in a try block, catch any/every exception, and call its printStackTrace() method. That way you can be sure of seeing all the details for any exception.
ya working. small size file ok. but how can send larger movie file 700mb(is it possible to send)..it shows exception.
server side:
C:\Users\Sathya>java FileServer Waiting. Accepted connection : Socket[addr=/192.168.1.6,port=50781,localport=13267] Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at FileServer.main(FileServer.java:16)
C:\Users\Sathya\test>java FileClient Connecting. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at FileClient.main(FileClient.java:16)
Java Socket Programming-File transfer through socket in Java
So far we have discussed the fundamental concepts of networking with Java . We also discussed the TCP and UDP modes of communication in Java with suitable examples.In previous chapters we were discussing a chat application in java and file transfer in Java using socket programming . But the file transfer example we discussed was not a standard one.In this chapter we are discussing a more enhanced version of the file transfer through socket in java example we discussed earlier .(File transfer can be done using UDP too. It is explained already with good example .Please see the post )
File transfer through socket in Java
Our application has a client and a server. Our aim is to send a file from the client machine to the server machine. In this case, we are sending the file as a java object.(We already discussed the way to transfer java objects through sockets before) . The object contains the file name , destination path , file content ,status of transfer etc. Lets see the FileEvent.java .We are sending the file with details as attributes of object of this class.
FileEvent.java
public class FileEvent implements Serializable
private static final long serialVersionUID = 1L;
private String destinationDirectory;
private String sourceDirectory;
private String filename;
private long fileSize;
private byte[] fileData;
private String status;
public String getDestinationDirectory() return destinationDirectory;
>
public void setDestinationDirectory(String destinationDirectory) this.destinationDirectory = destinationDirectory;
>
public String getSourceDirectory() return sourceDirectory;
>
public void setSourceDirectory(String sourceDirectory) this.sourceDirectory = sourceDirectory;
>
public String getFilename() return filename;
>
public void setFilename(String filename) this.filename = filename;
>
public long getFileSize() return fileSize;
>
public void setFileSize(long fileSize) this.fileSize = fileSize;
>
public String getStatus() return status;
>
public void setStatus(String status) this.status = status;
>
public byte[] getFileData() return fileData;
>
public void setFileData(byte[] fileData) this.fileData = fileData;
>
>
Now lets see the server code.It simply creates a ServerSocket on port 4445 and waiting for incoming socket connections.Once a connection comes , it accepts the connection.And then it is reading the FileEvent object. Destination directory , file etc are creating. Data is writing to the output file too. Then closing and exiting.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server private ServerSocket serverSocket = null;
private Socket socket = null;
private ObjectInputStream inputStream = null;
private FileEvent fileEvent;
private File dstFile = null;
private FileOutputStream fileOutputStream = null;
/**
* Accepts socket connection
*/
public void doConnect() try serverSocket = new ServerSocket(4445);
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
> catch (IOException e) e.printStackTrace();
>
>
/**
* Reading the FileEvent object and copying the file to disk.
*/
public void downloadFile() try fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase(«Error»)) System.out.println(«Error occurred ..So exiting»);
System.exit(0);
>
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) new File(fileEvent.getDestinationDirectory()).mkdirs();
>
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println(«Output file : » + outputFile + » is successfully saved «);
Thread.sleep(3000);
System.exit(0);
> catch (IOException e) e.printStackTrace();
> catch (ClassNotFoundException e) e.printStackTrace();
> catch (InterruptedException e) e.printStackTrace();
>
>
public static void main(String[] args) Server server = new Server();
server.doConnect();
server.downloadFile();
>
>
Now see the client code.It simply requests for a socket connection .After getting connection, it is creating the FileEvent object which contains the file details along with full content as byte stream.Then writing the FileEvent object to socket and exiting itself.
import java.io.*;
import java.net.Socket;
public class Client private Socket socket = null;
private ObjectOutputStream outputStream = null;
private boolean isConnected = false;
private String sourceFilePath = «E:/temp/songs/song1.mp3»;
private FileEvent fileEvent = null;
private String destinationPath = «C:/tmp/downloads/»;
/**
* Connect with server code running in local host or in any other host
*/
public void connect() while (!isConnected) try socket = new Socket(«localHost», 4445);
outputStream = new ObjectOutputStream(socket.getOutputStream());
isConnected = true;
> catch (IOException e) e.printStackTrace();
>
>
>
/**
* Sending FileEvent object.
*/
public void sendFile() fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf(«/») + 1, sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf(«/») + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) try DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read = 0) read = read + numRead;
>
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus(«Success»);
> catch (Exception e) e.printStackTrace();
fileEvent.setStatus(«Error»);
>
> else System.out.println(«path specified is not pointing to a file»);
fileEvent.setStatus(«Error»);
>
//Now writing the FileEvent object to socket
try outputStream.writeObject(fileEvent);
System.out.println(«Done. Going to exit»);
Thread.sleep(3000);
System.exit(0);
> catch (IOException e) e.printStackTrace();
> catch (InterruptedException e) e.printStackTrace();
>
public static void main(String[] args) Client client = new Client();
client.connect();
client.sendFile();
>
>
If connection is between two different computers , then in place of local host ,ip address of machine in which server is running needs to be given .
Output
The source file is E:/temp/songs/song1.mp3 . After running both Client and Server , the song1.mp3 will be there in C:/tmp/downloads/ in the machine where server is running.
Remember, this application cannot be used to transfer file of very huge size (say 300 MB or above). The maximum size of file that can be transferred depends on the capacity of JVM using.
Java write file to socket
- Language
- HTML & CSS
- Form
- Java interaction
- Mobile
- Varia
- Language
- String / Number
- AWT
- Swing
- Environment
- IO
- JS interaction
- JDBC
- Thread
- Networking
- JSP / Servlet
- XML / RSS / JSON
- Localization
- Security
- JNI / JNA
- Date / Time
- Open Source
- Varia
- Powerscript
- Win API & Registry
- Datawindow
- PFC
- Common problems
- Database
- WSH & VBScript
- Windows, Batch, PDF, Internet
- BigIndex
- Download
- TS2068, Sinclair QL Archives
- Real’s HowTo FAQ
- Donate!
- Funny 1
- Funny 2
- Funny 3
- Funny 4
- One line
- Ascii Art
- Deprecated (old stuff)
Transfer a file via Socket Tag(s): Networking
About cookies on this site
We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.
This example is very simple with no authentication and hard-coded filename!
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class SimpleFileServer < public final static int SOCKET_PORT = 13267; // you may change this public final static String FILE_TO_SEND = "c:/temp/source.pdf"; // you may change this public static void main (String [] args ) throws IOException < FileInputStream fis = null; BufferedInputStream bis = null; OutputStream os = null; ServerSocket servsock = null; Socket sock = null; try < servsock = new ServerSocket(SOCKET_PORT); while (true) < System.out.println("Waiting. "); try < sock = servsock.accept(); System.out.println("Accepted connection : " + sock); // send file File myFile = new File (FILE_TO_SEND); byte [] mybytearray = new byte [(int)myFile.length()]; fis = new FileInputStream(myFile); bis = new BufferedInputStream(fis); bis.read(mybytearray,0,mybytearray.length); os = sock.getOutputStream(); System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)"); os.write(mybytearray,0,mybytearray.length); os.flush(); System.out.println("Done."); >finally < if (bis != null) bis.close(); if (os != null) os.close(); if (sock!=null) sock.close(); >> > finally < if (servsock != null) servsock.close(); >> >
import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public class SimpleFileClient < public final static int SOCKET_PORT = 13267; // you may change this public final static String SERVER = "127.0.0.1"; // localhost public final static String FILE_TO_RECEIVED = "c:/temp/source-downloaded.pdf"; // you may change this, I give a // different name because i don't want to // overwrite the one used by server. public final static int FILE_SIZE = 6022386; // file size temporary hard coded // should bigger than the file to be downloaded public static void main (String [] args ) throws IOException < int bytesRead; int current = 0; FileOutputStream fos = null; BufferedOutputStream bos = null; Socket sock = null; try < sock = new Socket(SERVER, SOCKET_PORT); System.out.println("Connecting. "); // receive file byte [] mybytearray = new byte [FILE_SIZE]; InputStream is = sock.getInputStream(); fos = new FileOutputStream(FILE_TO_RECEIVED); bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; do < bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); if(bytesRead >= 0) current += bytesRead; > while(bytesRead > -1); bos.write(mybytearray, 0 , current); bos.flush(); System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)"); > finally < if (fos != null) fos.close(); if (bos != null) bos.close(); if (sock != null) sock.close(); >> >
To try it, first you start the server. You make sure that the file to be sent (as specified in SimpleFileServer) exists! Then you execute the client module.
To download a file, a simpler and better way is to use the built-in JDK HTTP server, see this HowTo