Sending file java socket

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

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?

Читайте также:  Символы переноса строки заменить php

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)

Источник

Sending file java 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

    Источник

    Java Socket Programming-Transferring large sized files through socket

    So far we have discussed the fundamentals of Socket programming . In a previous chapter we have discussed the file transfer using TCP . In that example we were converting the entire file object into byte array . And sending it through the socket.But that cannot be applied to large sized file.Because the heap of a JVM cannot afford an object beyond its maximum capacity.So for transferring large sized files we need to use another approach. In this chapter we are discussing about transferring large sized files through socket with suitable example.The file size does not have any limit in this case.So this application can be used to transfer movies of large or very large size.The java nio package has a SocketChannel component.We can use a SocketChannel instance for sending file. On the other side of connection , a ServerSocketChannel accepts the connection.Read/Write operations on a file is done with FileChannel instances

    Transferring large sized files through socket

    FileSender.java

    import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; public class FileSender < public static void main(String[] args) < FileSender nioClient = new FileSender(); SocketChannel socketChannel = nioClient.createChannel(); nioClient.sendFile(socketChannel); >/** * Establishes a socket channel connection * * @return */ public SocketChannel createChannel() < SocketChannel socketChannel = null; try < socketChannel = SocketChannel.open(); SocketAddress socketAddress = new InetSocketAddress("localhost", 9999); socketChannel.connect(socketAddress); System.out.println("Connected..Now sending the file"); >catch (IOException e) < e.printStackTrace(); >return socketChannel; > public void sendFile(SocketChannel socketChannel) < RandomAccessFile aFile = null; try < File file = new File("D:\\Test\\Video.avi"); aFile = new RandomAccessFile(file, "r"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (inChannel.read(buffer) >0) < buffer.flip(); socketChannel.write(buffer); buffer.clear(); >Thread.sleep(1000); System.out.println("End of file reached.."); socketChannel.close(); aFile.close(); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (InterruptedException e) < e.printStackTrace(); >> >

    FileReceiver.java

    import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class FileReceiver < public static void main(String[] args) < FileReceiver nioServer = new FileReceiver(); SocketChannel socketChannel = nioServer.createServerSocketChannel(); nioServer.readFileFromSocket(socketChannel); >public SocketChannel createServerSocketChannel() < ServerSocketChannel serverSocketChannel = null; SocketChannel socketChannel = null; try < serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); socketChannel = serverSocketChannel.accept(); System.out.println("Connection established. " + socketChannel.getRemoteAddress()); >catch (IOException e) < e.printStackTrace(); >return socketChannel; > /** * Reads the bytes from socket and writes to file * * @param socketChannel */ public void readFileFromSocket(SocketChannel socketChannel) < RandomAccessFile aFile = null; try < aFile = new RandomAccessFile("E:\\Test\\Video.avi", "rw"); ByteBuffer buffer = ByteBuffer.allocate(1024); FileChannel fileChannel = aFile.getChannel(); while (socketChannel.read(buffer) >0) < buffer.flip(); fileChannel.write(buffer); buffer.clear(); >Thread.sleep(1000); fileChannel.close(); System.out.println("End of file reached..Closing channel"); socketChannel.close(); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (InterruptedException e) < e.printStackTrace(); >> >

    Specify a valid file as source file in FileSender.java .Specify a valid and existing output folder at the FileReceiver.java while initializing the RandomAccessFile object.In the above code , we used localHost as address .We need to put suitable address there. Start the FileReceiver.java and then FileSender.java.The file would be sent from source to destination. These applications can be used to transfer large sized files (like .mkv , .mprg movies) from one machine to another.This application can be used to transfer files of all formats.

    9 thoughts on “ Java Socket Programming-Transferring large sized files through socket ”

    There is a typo in private void sendMessage(String message): It always sends “request” instead of “message”.

    Above program works well if the data is not huge say 20 mb or so. But I tried to move a movie and even though the file size is correct on the client but there is some data corruption. How can we enhance the client server to check for data corruption?

    Yes, think you have to replace the line in the ( ) for while with (inchannel.read(buffer) > 0 ) in the file sender and correspondingly in the file receiver program

    Источник

Оцените статью