Send a picture file using sockets

Hi,
Could someone please tell me how I can send a picture file using sockets across a TCP/IP network? I have managed to do it by converting the file into a byte array and then sending it but I dont see the data back at the client when I recieve the file. I just see the byte array as having size 0 at client.
Byte array size is correct at client side.
//client code
System.out.println("Authenticating client");
          localServer = InetAddress.getLocalHost();
          AuthConnection = new Socket(localServer,8189);
          out = new PrintWriter(AuthConnection.getOutputStream());
          InputStream is = AuthConnection.getInputStream();
          System.out.println(is.available());
          byte[] store = new byte[is.available()];
          is.read(store);
     ImageIcon image = new ImageIcon(store);
          JLabel background = new JLabel(image);
          background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
          getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
//extra code here
          catch (UnknownHostException e) {
System.err.println("Don't know about host: LocalHost");
System.exit(1);
          catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: LocalHost");
System.exit(1);
//server code
               DataOutputStream out = new DataOutputStream(incoming.getOutputStream());
               FileInputStream fin = new FileInputStream("3trees.gif");
               byte[] b = new byte[fin.available()];
               int ret = fin.read(b);
               out.write(b);

i used OutputStream as
OutputStream out = incoming.getOutputStream(); and flushed the stream too.
But I still get the same output on the client side. I tried sending a string and it works , but I cant seem to be able to populate the byte array on the client side. It keeps showing zero. Please advise.
Thank you.

Similar Messages

  • Sending a pdf file using submit without client email program.

    I need a solution on sending a completed pdf file to my email address without the clients email program poping up.  My website has a small pdf file that users can complete and return to me.  I get many complaints from users stating it requires them to save the file first and then they are unsure were it saved or how to attach it to a email.  To make this easer on my users I want the submit button to simply send me the file using some method from my website.  I use iPage to host the site now.  I was looking for a script to call or some way to do this automaticly.  I was woundering if urs/sbin/sendmail might work.  I am simply at a loss on this.

    Using a sendmail type script will send you the form data in the body of an email message, if the form is set up to submit as "HTML". You can create your own script to attach the form data as an FDF, XFDF, or even the complete PDF, but it's unlikely your provider supplies a script for this, so you'd have some custom programming to do.
    Sending just the form data also avoids the licensing restrictions for Reader-enabled forms. You can easily import an FDF or XFDF into a blank form to create a filled-in form.

  • Downloading a binary file using sockets without length known

    Hi all,
    I'm trying to download a binary(.exe) file using socket, where the length of the file is not known. Please take a look at the code I'm using:
          var readBin = socketBin.read();
         <-- Here comes the code that checks for http Content-length header field
         ; If content-length field is available, then I'll use it to download file, else proceed with following code -->
        pBar.reset("Downloading plugin..",null);pBar.hit(readBin.length);       
                while (1)
                    binFil.write(readBin);     //'binFil' is the file, into which downloaded file is written.
                    readBin = socketBin.read();
                    pBar.hit(readBin.length);
                    if( socketBin.eof || readBin.length<=0){
                        break;}          
                binFil.write(readBin);
                binFil.close();
                socketBin.close();
    Problem is: I'm able to download file within 10 seconds when content-length is known. But when content-length is not known, its taking about 1 and half minute to download, also the progress bar gets struck for much of time.
    FYI: socket is opened in binary mode, file is getting downloaded correctly(even though it takes abt a minute). BTW Im using CS5.5 extendscript
    I'm not able to figure out where the bug is.

    Hi, Srikanth:
    Sevaral points.
    #1 When posting code, please use the web interface and the >> icon and choose Syntax Highlighting >> Java. Otherwise your code is just too hard to read and gets misformatted.
    #2 Apropos of #1, your script as written does not work, because this line:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$ 1/$2/$3/$4");
    has an extra space in the $1 and should be this:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$1/$2/$3/$4");
    Please take an extra moment to make sure that when you asking for help, you do so in a way that makes sense. Otherwise it takes too much effort to help you, and that is frustrating.
    #3 If we instrument your script by adding a line to the while() loop:
                while (1)
                    binFil.write(readBin);
                    readBin = socketBin.read();
                    $.writeln(Date()+" Read "+readBin.length+" chars, eof is "+socketBin.eof);
                    if(  readBin.length<=0){         break;}              
    We get output like this:
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 631 chars, eof is false
    Mon Jul 11 2011 12:07:06 GMT-0400 Read 0 chars, eof is false
    Result: undefined
    Therefore, we can reasonably conclude that the last read at the end of the data stream returns a short read when the other side blocks.
    Unfortunately, that's clearly insufficient since you can get short reads all the time.
    I'm not sure why you say the length of the file is not known, HTTP provides it to you in the Content-Length field of the response.
    But the easy answer is to get the server to close it for you. This is easy, enough, with Connection: close. Why were you specifying
    Connection: keep-alive, anyhow?:
                var requestBin =
                "GET /" + parsedURLBin.path + " HTTP/1.1\n" +
                "Host: " + parsedURLBin.address + "\n" +
                "User-Agent: InDesign ExtendScript\n" +
                "Accept: */*\n" +
                //"Connection: keep-alive\n\n";
                "Connection: close\n"+
                "\n";
    This yields a nice tidy:
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 735 chars, eof is true
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 0 chars, eof is true
    I suspect you're also better off using something like socketBin.read(64*1024) for a 64k buffer size, but it doesn't seem to effect the on-the-wire protocol, so perhaps its not so important.
    If you don't want to reply on the server

  • Oracle BAM to monitor transfer of files using sockets

    Hi,
    We have two programs transferring files using sockets. We wanted BAM to monitor the transfer.
    Would you please suggest if this is achievable in BAM , and if so , any pointers to how we may go about implementing it .
    Cheers,
    Anant.

    You could generate success/failure/progress from your utility to JMS or call BAM webservices to populate BAM Data Objects. Reports could be built on top of that.

  • Moving Files using sockets

    I wanted to know of a good way to move, not copy, files using sockets? Any help would be great.
    Thanks

    Even on the same machine, you can only move a file on the same filesystem. i.e. the file appears in a different directory rather than copying the file.
    If you have an C: and D: drive for example it will copy and delete the file on a move.
    Unix allows you to have symbolic links which can make a file/directory from anywhere appear anywhere on your filesystem. It does not copy or actaully move the file, it just appears to be where ever you choose.

  • TS3276 why i can't send a Pages file using gmail

    i can't send Pages attach file using gmail imap server

    Google blocks the new iwork files :(
    And there is no responce yet when they fix it
    Solution!!!:
    1 - Send it by exporting to office files
    2 - Saving the files as old iwork documents
    3 - Command P and save as PDF
    4 - Save in icloud and send the URL

  • Sending file using sockets (difficult)

    Hi, i have the following section of code
    (of which i am not claiming ownership) which
    implements a DCC Send command from irc.
    It accomplishes this using sockets, and while
    i understand how the code accomplishes what it
    does, i need help with a possible modification.
    Basically what i am looking to do is keep track
    of the progress of the send - so that the
    user can at any time see how much of the file
    has been sent and how much is remaining.
    If anyone has done such a thing in the past or
    has a good idea as to how this should be implemented,
    i would be greatful for their help.
    Here is the code:
    new Thread() {
                public void run() {
                    try {
                        ServerSocket ss = new ServerSocket(0);
                        ss.setSoTimeout(timeout);
                        int port = ss.getLocalPort();
                        //byte[] ip = ss.getInetAddress().getAddress();
                        byte[] ip = InetAddress.getLocalHost().getAddress();
                        long ipNum = 0;
                        long multiplier = 1;
                        for (int i = 3; i >= 0; i--) {
                            int byteVal = (ip[i] + 256) % 256;
                            ipNum += byteVal*multiplier;
                            multiplier *= 256;
                        // Rename the filename so it has no whitespace in it when we send it.
                        // .... I really should do this a bit more nicely at some point ....
                        String safeFilename = file.getName().replace(' ', '_');
                        safeFilename = safeFilename.replace('\t', '_');
                        // Send the message to the user, telling them where to connect to in order to get the file.
                        sendCTCPCommand(nick, "DCC SEND " + safeFilename + " " + ipNum + " " + port + " " + file.length());
                        // The client may now connect to us and download the file.
                        Socket socket = ss.accept();
                        socket.setSoTimeout(30000);
                        // Might as well close the server socket now; it's finished with.
                        ss.close();
                        BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
                        BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
                        BufferedInputStream finput = new BufferedInputStream(new FileInputStream(file));
                        byte[] outBuffer = new byte[bufferSize];
                        byte[] inBuffer = new byte[4];
                        int bytesRead = 0;
                        while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
                            output.write(outBuffer, 0, bytesRead);
                            output.flush();
                            input.read(inBuffer, 0, inBuffer.length);
                        output.close();
                        input.close();
                        log("+++ DCC SEND Completed to " + nick + " (" + file.getPath() + ")");
                    }

    You already have the necessary code to find the number of bytes sent at any point during the transmission. You can find out the size of the file by instantiating a RandomAccessFile before you send it, and querying for the file length.
    I suggest you make the file size and bytes sent volatile and conveniently accessible to another thread (best implemented here as an inner class?). Your new thread will need to monitor the file transfer at intervals to update the progress indicator. You can generate estimates of time remaining by measuring the average transmission rate, and extrapolating using the total file size. Classically this is done using an average, but you might be better just maintaining a list of fairly recent samples, allowing for the speed swings inherent in internet connections.
    How you update the progress indicator from your monitor thread is up to you. I suggest exposing methods in the UI for setting the progress and time remaining, and simply update them from the monitor.
    Does this help any?

  • Reading / Writing files using Sockets

    Hi there guys,
    I am fairly new to this forum. I have been having a problem for the past three days. I am implementing a client/server implementation using Sockets which is a submodule of a project I am working on. What I want is that a files content are read and transferred over the network to the server that writes it down to a different file .
    What the code presently does is :
    <<<<Client Code >>>>
    It reads a file input.txt and sends the content over the network to the server.
    <<<< Server Code >>>
    It reads the incoming data from the client and writes the data out to a file called output.txt
    What I want now is that the server should read the file output.txt and send the contents to the client which reads it and then writes it down as a new file called serverouput.txt . After that I want to compare and see of the size of input.txt and serveroutput.txt . If both are same that means that data has been written reliably to the server.
    I have been trying to implement it for a long time and nothing seems to work out. I am posting the code for both client and server below. Any help in finalising things would be really appreciated.
    CLIENT CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class sc {
    static final int PORT = 4444;          //Change this to the relevant port
    static final String HOST = "127.0.0.1";
         //Change this to the relevant HOST,
    //(where Server.java is running)
    public static void main(String args[]) {
    try {
    System.out.print("Sending data...\n");
    Socket skt = new Socket(HOST, PORT);
                   // Set the socket option just in case server stalls
    skt.setSoTimeout ( 2000 );
                   skt.setSoKeepAlive(true);
    //Create a file input stream and a buffered input stream.
    FileInputStream fis = new FileInputStream("input.txt");
    BufferedInputStream in = new BufferedInputStream(fis);
    BufferedOutputStream out = new BufferedOutputStream( skt.getOutputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
                   // Enable SO_KEEPALIVE
    out.flush();
    out.close();
    in.close();
    skt.close();
    catch( Exception e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
              catch( IOException e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
    SERVER CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class ClientWorker implements Runnable {
    private Socket client;
    ClientWorker(Socket client) {
    this.client = client;
    public void run(){
    try      {
    FileOutputStream fos = new FileOutputStream("output.txt");
    BufferedOutputStream out = new BufferedOutputStream(fos);
    BufferedInputStream in = new BufferedInputStream( client.getInputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
    System.out.println("Receiving data...");
    out.flush();
    in.close();
    out.close();
    client.close();
    // srvr.close();
    System.out.println("Transfer complete.");
    catch(Exception e) {
    System.out.print("Error! It didn't work! " + e + "\n");
    class ss1 {
    ServerSocket server = null;
    ss1(){ //Begin Constructor
    } //End Constructor
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    while(true){
    ClientWorker w;
    try{
    w = new ClientWorker(server.accept());
    Thread t = new Thread(w);
    t.start();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    protected void finalize(){
    //Objects created in run method are finalized when
    //program terminates and thread exits
    try{
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close socket");
    System.exit(-1);
    public static void main(String[] args){
    ss1 frame = new ss1();
         frame.listenSocket();
    }

    ............................................. After that I want to
    compare and see of the size of input.txt and
    serveroutput.txt . If both are same that means that
    data has been written reliably to the server.You don't need to do this. TCP/IP ensures the reliable transmition of data. By using a socket you are automaticaly sure that the data is reliably transmitted (Unless there is some sort of exception).
    To get the size of the files you can use a File object. Look it up in java.io package in API documentation.
    java-code-snippet (without error checking)
    File clientFile = new File("input.txt");
    clientFile.length();

  • How to Transfer files using socket remote method invocation?

    hello guys,
    i am working on java sockets...and i need to send and receive files though Java RMI. how will i go with it....
    Please do help me in this regard
    Edited by: sandeep_genevsoftech on Apr 4, 2008 4:32 AM

    I am also developing a similar application of file transfer but using sockets in place of RMI.The file gets transfered if i run client and server on same m/c(as localhost),but shows "access denied" if run on different m/c.I suppose some security policies need to be set.Can anybody help?

  • Strange behaviour sending a text file over sockets

    Hi !
    Im not exactly new to Java. I discovered this behaviour when explaining to a junior.
    I have a simple Server-Client architecture to send a text file. The server sends strings to client. The client checks for the string to become null, and never terminates !
    Server.java
    ServerSocket ss = new ServerSocket(25780);
    Socket s = ss.accept();
    PrintStream ps = new PrintStream(s.getOutputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedReader fis = new BufferedReader(
                   new InputStreamReader(
                        new FileInputStream(filename)));
    while((read = fis.readLine()) != null){
         ps.println(read);
    client.java
    Socket s = new Socket(IP,port);
    PrintStream ps = new PrintStream(s.getOutputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String read = new String();_
    *while((read = br.readLine())  != null){*_
    System.out.println(read);_
    Can you tell me what mistake I'm making?

    Thank you so much for the reply !
    All blocks are within try-catch. I didn't post the whole code since you would find it inconvenient !
    I tried flushing the stream ! Still doesnt work !
    I guess it might help to post the entire source:
    CLIENT.JAVA
        public static void main(String[] args) {
         try{
             System.out.println("Client");
             int port  = 25780;
             String IP = new String("127.0.0.1");
             Socket s = new Socket(IP,port);
             PrintStream ps = new PrintStream(s.getOutputStream());
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
             String command = new String();
             String filename_to_recv = "from_ser.txt";
             command = "GET "+filename_to_recv;
             ps.println(command);
             String received = new String();
             String read;
             while((read = br.readLine()) != null){
              System.out.println(read);
             String filename_to_send = "from_cli.txt";
             System.out.println("recd data from server");
             command = "PUT "+filename_to_send;
             ps.println(command);
             BufferedReader filereader = new BufferedReader(
                                 new InputStreamReader(
                                  new FileInputStream(filename_to_send)));
             String to_send = new String();
             while((to_send = filereader.readLine()) != null){
              ps.println(to_send);
             try{
               Thread.sleep(2000);
             } catch(Exception e){
              System.out.println(""+e);
              e.printStackTrace();
         } catch(Exception e){
             System.out.println(""+e);
             e.printStackTrace();
    SERVER.JAVA
       public static void main(String[] args) {
         try{
             System.out.println("Server");
             ServerSocket ss = new ServerSocket(25780);
             Socket s = ss.accept();
             PrintStream ps = new PrintStream(s.getOutputStream());
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
             String command = br.readLine();
             String filename = command.substring(command.indexOf(' ')+1);
             File f = new File(filename);
             BufferedReader fis = new BufferedReader(
                            new InputStreamReader(
                             new FileInputStream(filename)));
             String read;
             while((read = fis.readLine()) != null){
              ps.println(read);
             ps.flush();
             System.out.println("waiting for client data");
             command = br.readLine();
             while((read = br.readLine())  != null){
              System.out.println(read);
         } catch(Exception e){
             System.out.println(""+e);
             e.printStackTrace();
        }

  • Need to send the text file using webservice

    Hi,
    I want to send the text file with contains data through oracle pl/sql using webservice. How can i handle this program?
    Kindly share with your details.
    Thanks in advance,
    Maran

    user8732035 wrote:
    I want to send the text file with contains data through oracle pl/sql using webservice. How can i handle this program?Web services supply XML structured data. Not text files.
    PL/SQL supports web services (XML output) and web procedures (text and binary output).
    You need to clarify your requirements.

  • Need to send mail & upload files using JSP

    hi, got a lot of issues,.. just starting out as a developer.. so here goes.
    1st Need to send mail & upload files to server using JSP(tomcat).. an example to demo it would be nice.
    thanx in advance

    Look at this for email:
    http://forum.java.sun.com/thread.jspa?forumID=45&threadID=285950
    and go to:
    http://servlets.com/cos/
    for a package to upload files.

  • Sending jpeg (pictures) files from my phone to my hotmail email come thru as txt files, but works fine with my friends

    Picture files sent from my phone come thru as txt files to my email instead of jpeg. but when I copy to others it goes thru as jpeg fine.

    Sorry let me correct something and give you some additional info. First I spelled .jpg wrong, and second my phone will send pictures to my mail 60 or so % of the time as .jpg and everything is fine but for no apparent reason some times they go thru as ,txt to my hotmail account email. I will also add if I copy a friend with the same picture they will get it as .jpg and be fine.

  • Sending few avi files using rtp to specific ip:port

    Hi all,
    I need to transmit a series of avi files using rtp to a specific ip & port which RTP reciever is waiting.
    Can anyone direct me thruogh JMF?
    Thanks,
    Lior.

    Is there a way to send JPEG files thruogh the RTP session and gather them to movie on the receiver side.
    (I mean send images one by the other from a specific path).
    Lior.

  • Send a text file using  MF SO_NEW_DOCUMENT_ATT_SEND_API1

    HI.
    I am trying send a file text from a internal table using the MF: SO_NEW_DOCUMENT_ATT_SEND_API1, the code for tranfer the internal table   is:
    LOOP AT i_bultos_inex2.
          mailbin-line(20) = i_bultos_inex2-cod_bulto.
          mailbin-line+20(8) = i_bultos_inex2-fecha.
          mailbin+254(1) = cl_abap_char_utilities=>cr_lf.
          APPEND mailbin.CLEAR mailbin.
        ENDLOOP.
    In the file send by e-mail, the lines are not adjusted to the left and each line of the internal table not is a line in the file text.
    How i can solved?
    Thanks.

    Hi,
    Try to use
        call function 'SCMS_STRING_TO_FTEXT'
          exporting
            text      = string
          tables
            ftext_tab = mailbin.
    I think you are not working unicode system

Maybe you are looking for

  • I need to specifiy the end of line in a delete comand in sed.

    Hi, With the substitute option ,s, I can do it easily with \\$.  Example is sed ' s\Serial0\/0\\$\Serial0\/1\g This replaces Serial0/0 with Serial 0/1 globally only if Serial0\0 is the whole string to the end of the line i.e. it won't match Serial0/0

  • Request Native Ability to Calculate CRC, MD5, and SHA Hashes

    // Requested via the Feedback tool also // Provide the ability to calculate and generate CRC, MD5, and SHA hashes via a right-click context menu without having to resort to third party tools.  In some environments, policy does not allow for certain a

  • Simple question - How do I fade out a project?

    There's got to be an easy answer to this. I have created a project in Logic 9 and would like to fade it out at the end. This is really easy in GarageBand (Track > Fade Out) but I can't see how to do it in Logic. Any tips?

  • Search Functionality

    Hi All, Is it possible to search all the columns of a table with particular value(without using or functionality in query)? For ex. I have multiple columns(contains more than 10 values) in a table. IFE_ID Locale Name Cate Movid F Y S SubCate ife_deta

  • Cant install Beta CS6 in Windows7, help please

    I have dowloaded the window files 3 times. They appear as a bunch of zip files and any attempt to unzip them is unsucessful. What am I doing wrong?