Image transfer through *socket*

hi.
can anyone plz show how to send a PNG image file through a raw socket outputStream (from a j2se server to a midlet) ???
thanks

You will have to take care of indentation.
midlet code:
//SOCKET ---------------------------------------------------------------
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class Main extends MIDlet implements Runnable
     private Thread t;
     private Display display;
     private Form form;
     private Command exitCommand, getCommand;
     private String connectionDetails "socket://10.10.100.109:1500";
     private InputConnection ic;
     private DataInputStream dis;
     public Main()
          //create the backCommand, okCommand and the exitCommand
          exitCommand = new Command("Exit", Command.EXIT, 1);
          //creating the form
          form = new Form("CONNECTING......");
          form.addCommand(exitCommand);
          System.out.println("exit command and get command were appended to the form");
          //instantiating the listener
          CommandListener listener = new CommandListener()
               public void commandAction(Command c,Displayable d)
                    if(c==exitCommand)
                         System.out.println("exitCommand as pressed");
                         exit();
               public void exit()
                    destroyApp(true);
                    notifyDestroyed();
          //setting the listeners
          form.setCommandListener(listener);
          //getting the display object
          display = Display.getDisplay(this);
     public void startApp()
          display.setCurrent(form);
          System.out.println("form was set as the currentscreen");
          t = new Thread(this);
t.start();
     public void pauseApp()
     public void destroyApp(boolean cond)
          display = null;
          form = null;
          exitCommand = null;
public void run()
     while(true)
                              try
                                   //establishing a connection with the remote server
                                   System.out.println("about to get a stream connection");
                                   ic = (InputConnection)Connector.open(connectionDetails,Connector.READ);
                                   System.out.println("input connection was created");
                                   //input stream is created on top
                                   //of the stream connection object
                                   dis = ic.openDataInputStream();
                                   System.out.println("input stream was created");
                                   //receiving data
                                   byte []ib = new byte[10000];
                                   int length = dis.read(ib);
     System.out.println("BYTES RECEIVED "+length);
     /*for(int k= 0;k<length;k++)
          System.out.println("byte["+k+"]="+ib[k]);
                                   //displaying the received data
                                   if(form.size()!=0)
                                        form.delete(0);
                                   form.append(Image.createImage(ib,0,length));
                                   //form.append(new StringItem("DOLLAR NIS exchange rate is ", sb.toString()));
                              catch(Exception e)
                                   if(form.size()!=0)
                                        form.delete(0);
                                   form.append(new StringItem("problem:",e.getMessage()));
                              finally
                                   //releasing resources that were allocated
                                   try
                                        if(dis!=null)
                                             dis.close();
                                   catch(IOException e)
                                        e.printStackTrace();
                                   try
                                        if(ic!=null)
                                             ic.close();
                                   catch(IOException e)
                                        e.printStackTrace();
               try{Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Server code:
// tcpServer.java by fpont 3/2000
// usage : java tcpServer <port number>.
// default port is 1500.
// connection to be closed by client.
// this server handles only 1 connection.
package sock;
import java.net.*;
import java.io.*;
public class ImageServer {
     public static int counter = 0;
     public static final int counter_end = 4;
public static void main(String args[]) {
     int port;
     ServerSocket server_socket;
     BufferedReader input;
     OutputStream output;
     try {
     port = Integer.parseInt(args[0]);
     catch (Exception e) {
     System.out.println("port = 1500 (default)");
     port = 1500;
     try {
     server_socket = new ServerSocket(port);
     System.out.println("Server waiting for client on port " +
               server_socket.getLocalPort());
     // server infinite loop
     while(true) {
          Socket socket = server_socket.accept();
          System.out.println("New connection accepted " +
                    socket.getInetAddress() +
                    ":" + socket.getPort());
          //input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = socket.getOutputStream();
          // print received data
          try
byte []ib=getCurrentFileBytes();
System.out.println("BYTES TO SEND "+ ib.length);
output.write(ib);
output.flush();
output.close();
          catch (IOException e) {
          System.out.println(e);
          // connection closed by client
          try {
          socket.close();
          System.out.println("Connection closed by client");
          catch (IOException e) {
          System.out.println(e);
     catch (IOException e) {
     System.out.println(e);
private static byte[] getCurrentFileBytes() throws IOException
          byte []ret = getFileBytes("c:/temp/ts"+counter+".png");
          if(counter == counter_end)counter = 0;
          else counter++;
          return ret;
private static byte[] getFileBytes(String FileName) throws IOException
          byte[] lReturn = null;
          try
               FileInputStream fis = new FileInputStream(FileName);
               lReturn = getBytes(fis);
               fis.close();
          catch(Exception e)
               e.printStackTrace();
               throw new IOException();
          return lReturn;
private static byte[] getBytes(InputStream inputStream)
byte finalBuffer[] = null;
int receiveBufferSize = 1000;
byte receiveBuffer[] = new byte[receiveBufferSize];
int offset = 0;
int length = 0;
int bytesRead = 0;
try
while(inputStream.available() > 0)
bytesRead = inputStream.read(receiveBuffer,offset,
receiveBufferSize);
byte temp[] = new byte[length + bytesRead];
if(length>0)System.arraycopy(finalBuffer,0,temp,0,length);
System.arraycopy(receiveBuffer,0,temp,length,bytesRead);
finalBuffer = temp;
length = length + bytesRead;
catch(IOException ioe)
ioe.printStackTrace();
finalBuffer = new byte[0];
return finalBuffer;

Similar Messages

  • Problem on image transfer using Socket

    There are a server and a client,
    server executes the code:
    ImageIO.write( bufferedImage, "jpg", outputStream );
    System.out.println("writed");client executes the code:
    BufferedImage bufferedImage = ImageIO.read( inputStream );
    System.out.println("read");The problem is that the string "writed" is displayed at the console of the server, but the client is blocking at the method ImageIO.read().
    However, when I add one more line of code to the server:
    ImageIO.write( bufferedImage, "jpg", outputStream );
    outputStream.close();
    System.out.println("writed");The problem is solved but I don't want to close the outputStream.
    I would like to ask is there any idea to solve this problem without close the outputStream?
    Thank you very much.

    I would like to ask is there any idea to solve this
    problem without close the outputStream?Send a message not data.
    You now just shove data down the pipe. The other end has no way to know when the data has arrived.
    Wrapping data in a message provides a way to determine that all of the data has arrived. This also means that you need a communication API. That is an api that
    1. Takes data as input
    2. Packages it in a message.
    3. Sends the message.
    4. Recieves a message
    5. Unpackages the data
    6. Returns the data as output.

  • Send a image through socket method getoutputstream

    cani send an image through socket methods instead of send a txt

    1) Use the search feature, or look back a couple of pages, this question was asked sometime yesterday
    2) In all the many times that it's been asked, no-one denies it but at the same time no-one's posted any code to do it (AFAIK) I'd be interested too if anyone does find a way...

  • Transfering a file through Socket programming

    Hi all,
    I want to return a file from server to client through a socket. I tried using ObjectOutput Stream where in I returned a java.io.File from server. But at client side when I say file.getLeangth() it comes as 0 and if I try to assign FileInputStream on the object it throws an exception as the file not found as the path associated with the file will be of Server.
    So can anyone help as to how to transfer a file through socket programming???
    thx in advance
    MK

    java.io.File is NOT the contents of the file. It really just represents the path.
    If you want to transfer the file's contents, you'll have to use a FileInputStream or FileReader, read from it, and then write the bytes or chars on the wire.

  • File thansfer through socket problem

    i am writing server /client program, where the server wait for client request to send or receive file through socket.
    can i use 1 socket to handle the request (client want to send or download file) and file data transfer?
    if yes, how to handle the beginging of file transfer after receive a request?
    and how can server know when the file transfer is completed?

    This tutorial should help:
    http://java.sun.com/docs/books/tutorial/networking/index.html

  • File reading through Sockets???

    Hello,
    My application has a server and it has to read a file that is sent by the client.. how can the server read a file sent by the client through sockets?????
    Edited by: s_coder on Feb 19, 2009 11:20 PM

    s_coder wrote:
    Yes i read it but there input is given from the client to the server through the standard input stream.... how can i transfer a file thru the standard input stream? and the accept it at the server side???Come on mate. You need to be able to add two and two on your own.
    WTF is a "standard input stream"? And why if you followed the tutorial can you not figure out how to send the data of a file through a socket?
    Either you didn't really read the tutorial or you're pretty darn hopeless. Why don't you try and really follow the tutorial, not just glance at each page but understand what it is saying. Then make an attempt to write your program and if you get stuck come back with your code. Be sure to use the code formatting tags when you show us your code.

  • Tansfer files through socket

    Hi all
    Can anyone tell me that how can i send files from server to the client through socket programming.
    if u recommend to send file using
    int read(byte[] b, int offset, int blength)
    void write( byte[] b, int offset, int blength) then how plz tell me how can use these methods to send a receive files??? if u give a small example code then i will very greatful to u.
    Usman

    Thanks for ur help.
    but i have got it. i have designed a client and server. Client requests the server to send a specif file (Client takes the path of file from user). And server sends the file to the client.
    I have checked this program on many files. like *.exe, *.txt, *.dat, *.zip, *.mp3, *.jpg.
    it worked smoothly. I have test to trasfer a file of 700MB and it worked correctly.
    Ooops! i did not check it on Network. i run these program on my own computer. both client and server were running on same computer.
    but i am facing a little problem. that is: the speed of trasfering the files is very slow.
    any1 know how to increase the speed of data transfer over the sockets ???
    And plz tell me how can i trasfer a complete directory just as i trasfered file over the sockets. (Remember: a dircetory may or may not contains may other files and also other directories
    thanks in advance...!!!
    here is the code:
    *          CLIENT            *
    import java.net.*;
    import java.io.*;
    public class TransferClient
        public static void main(String[] args)
            try
                 int fileSize = 0;
                 int readBytes = 0;     
                 final int BUFFER_SIZE = 512;
                 byte[] buffer = new byte[BUFFER_SIZE];       
                   Socket sockClient = new Socket(InetAddress.getLocalHost(),2000);     
                   DataInputStream dataInputStream = new DataInputStream(sockClient.getInputStream());
                   BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("filename.ext"));
                   BufferedReader inputUser   = new BufferedReader(new InputStreamReader(System.in)); //For User input
                   PrintWriter output = new PrintWriter (sockClient.getOutputStream(), true);     //To send the user input to the server
                   //get path from user
                   System.out.print("Enter the complete path of file: ");
                   String path = inputUser.readLine();
                   //send path to server
                   output.println(path);
                   readBytes = dataInputStream.readInt();
                   while(readBytes > 0)
                        readBytes = dataInputStream.read(buffer, 0, readBytes);
                        fileSize = fileSize + readBytes;
                        bufferedOutputStream.write(buffer, 0, readBytes);
                        readBytes = dataInputStream.readInt();
                   }//end while
                   bufferedOutputStream.flush();
                   System.out.println("Received Bytes:  " + fileSize);
                   dataInputStream.close();
                   bufferedOutputStream.close();                              
                   inputUser.close();
                   output.close();
                   sockClient.close();
            }//end try
            catch(IOException ioException)
                 ioException.printStackTrace();
            }//end catch
        }//end main()
    }//end class TransferClient
    *          SERVER            *
    import java.io.*;
    import java.net.*;
    public class TransferServer
        public static void main(String[] args)
             int fileSize = 0;         
             int readBytes = 0;
             final int BUFFER_SIZE = 512;
             byte[] buffer = new byte[BUFFER_SIZE];
             try
                  ServerSocket ss = new ServerSocket(2000);
                  System.out.println("Server Strarts...");
                  Socket sock = ss.accept();
                  BufferedReader clientInput = new BufferedReader(new InputStreamReader (sock.getInputStream()));
                   DataOutputStream dataOutputStream = new DataOutputStream(sock.getOutputStream());
                   PrintWriter output = new PrintWriter(sock.getOutputStream(), true);
                   System.out.println ("Connection Received");          
                   String path = clientInput.readLine();               
                   File f = new File(path);                    
                   if( f.exists() )
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path));               
                        while((readBytes = bufferedInputStream.read(buffer))!= -1)
                             fileSize = fileSize + readBytes;
                             dataOutputStream.writeInt(readBytes);
                             dataOutputStream.write(buffer, 0, readBytes); 
                        }//end while
                        dataOutputStream.writeInt(0);          
                        System.out.println("Sent Bytes:  " + fileSize);
                        bufferedInputStream.close();
                   }//end if
                   clientInput.close();
                   dataOutputStream.close();
             }//end try
             //catch(FileNotFoundException fileNotFoundException)
             //     output.println("Sorry! file does not exist.");
             catch(IOException ioException)
                  ioException.printStackTrace();
             }//end catch       
        }//end main()
    }//end class TransferServer

  • HELP! n95 image transfer problem!

    i have recently installed pc suite onto vista. previously pc suite worked fine when i had xp. now when i try to store images from phone to pc it tells me there is an error communicating with phone. pls help!

    suite version and step by step how you try to do that image transfer.
    Also what connection method (if USB, what mode you are choosing from phone)

  • Delivery cost for Stcok transfer through M.type : 351

    Hi Experts,
    Can anybody explain how to capture the delivery costs for Stock transfer through M.Type 351.
    Also kindly explain the steps involved in configuration of the same.
    Thanks in advance,
    Prabu

    Hi,
    Once the Config releated to Setup stock transfer order is done.
    To include the cost you need to include the pricing procedure related to STO needs to be assigned to your schema group.
    Goto SPRO -MM-Purchasing -- Conditions
    Here you need to assign the Schema determination RM2000 to your Purchasing organization.
    Then when you create the STO in the recieiving plant, then you will get the condition tab in the item details of STO, there you can maintain the delivery costs for that material & send the STO to your supplying plant.
    Supplying plant will send the material through MB1B & with mvt type 351 to recieving plant.
    At the time of Goods reciept system will capture the delivery costs in the recieving plant for that STO.
    rgds
    gsc

  • Can't connect to local MySQL server through socket '/var/mysql/mysql.sock'

    I'm using the pre-installed versions of php and mysql under Mac OS X Server 10.4.4 running on a G4 and am unable to get anything involving mysql to work.
    I ssh to the server and enter various commands in Terminal:
    on typing "mysql" I get
    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)
    and on typing "mysqladmin version" I get
    mysqladmin: connect to server at 'localhost' failed
    error: 'Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)'
    Check that mysqld is running and that the socket: '/var/mysql/mysql.sock' exists!
    On typing "sudo mysqld_safe" I get
    Starting mysqld daemon with databases from /var/mysql
    STOPPING server from pid file /var/mysql/MyServer.local.pid
    070722 16:06:05 mysqld ended
    /var/mysql/MyServer.local.err contains
    070722 16:06:04 mysqld started
    070722 16:06:04 [Warning] Setting lowercase_tablenames=2 because file system for /var/mysql/ is case insensitive
    070722 16:06:04 InnoDB: Database was not shut down normally!
    InnoDB: Starting crash recovery.
    InnoDB: Reading tablespace information from the .ibd files...
    InnoDB: Restoring possible half-written data pages from the doublewrite
    InnoDB: buffer...
    070722 16:06:05 InnoDB: Starting log scan based on checkpoint at
    InnoDB: log sequence number 0 43634.
    /var/mysql has permissions 775.
    The line
    mysql.default_socket = /var/mysql/mysql.sock
    is in /etc/php.ini
    whereis mysqladmin ->
    /usr/bin/mysqladmin
    whereis mysql ->
    /usr/bin/mysql
    ls /var/mysql ->
    MyServer.local.err
    ib_logfile1
    mysql
    ib_logfile0
    ibdata1
    test
    Can't find my.cnf or my.ini anywhere
    Can't find mysql.sock anywhere
    I'm trying to get a bug database running (mantis) under Mac OS X Server 10.4.4 that I can access from local clients.
    I'm trying to follow directions at http://www.mantisbugtracker.com/manual/manual.installation.php
    without knowing anything about mysql or php and I'm stuck on step 3:
    "Next we will create the necessary database tables and a basic configuration
    file."
    I get a message saying
    "Does administrative user have access to the database? ( Lost connection to MySQL server during query )"
    I don't even know if following the mantis directions has resulted in the creation of a database or not. Where would it be?
    Thanks for any help.
    Intel iMac   Mac OS X (10.4.10)  

    I've just done a clean install of OSX Server and added the latest MYSQL packaged installer. Afterwards I found the lock file in /private/tmp/mysql.lock
    The easiest way to solve this problem is to create a symbolic link so that the lock file appears to be in right place.
    e.g.
    cd /var
    sudo mkdir mysql <== this assumes the directory is missing
    cd mysql
    sudo ln -s /private/tmp/mysql.sock mysql.sock
    After this msql commands should work fine, and you've not fiddled with the security settings on users/groups.
    HTH
    Christian

  • How to send image file through mail without   any attachment

    Plz tell  me how to send image file through mail without any attachment  ( i mean not converting  that image into pdf or any format )  i want to send that text or image  through mail .

    Hi Sandeep,
    I think you can setup the type of email in Shared office Settings in transaction S016.
    There is an option called <Preset document classes>
    You choose this pushbutton to branch to the maintenance screen for the document classes that are directly displayed to users in the Business Workplace for selection when they use the Create function. The name under which the documents are displayed can also be maintained.
    http://help.sap.com/saphelp_nw70/helpdata/en/6c/69c30f418d11d1896e0000e8322d00/content.htm
    Haven't tried it though.
    Regards,
    Siddhesh

  • "Can't connect to local MySQL server through socket '/tmp/mysql.sock'"

    Data Services=3.1
    Repository=12.2.2.0000
    Red Hat Enterprise 5
    Designer,Job Server,Job Engine=12.2.2.3
    After an unscheduled server reboot with DS up and running when trying to start a job in either Data Services Management Console or DS Designer getting the following:
    "Can't connect to local MySQL server through socket '/tmp/mysql.sock'"
    The mysql.sock have never been in /tmp and on the production server it does not exist there and the production server is up and running correctly. If a link is created to mysql.sock(/home/user/boedge31/bobje/mysql) the job will start but return this message: 
    "Cannot retrieve <Version> from the repository. Additional database information: <SQL submitted to ODBC data source <localrepo> resulted in error <MySQL ODBC 3.51 Driver mysqld-5.0.46-enterprise No database selected>. The SQL submitted is <select VERSION, SECURITYKEY, GUID from AL_VERSION where NAME = 'Repository Version'"
    I checked and AL_VERSION and the Version field exist. 
    Before the shut down DS was working correctly and had no issues.  My best guess is a part of the repository was corrupted during the unscheduled shut down.  It seems like DS has "forgotten" some of the settings.  
    Any suggestions on a possible solution?

    The issue has been solved. 
    There was a bad path in $LD_LIBRARY_PATH.
    Removed the path and DS started working again.

  • Logging through sockets

    Hi
    I'm trying to send logging information through sockets using log4j.
    My configuration file is :
    log4j.rootLogger=Debug, Socket
    log4j.appender.Socket=org.apache.log4j.net.SocketAppender
    log4j.appender.Socket.Port=12345
    log4j.appender.Socket.RemoteHost=localhost
    log4j.appender.Socket.LocationInfo=true
    the server only reads the input string that the logger sends.
    I'm getting this exception on the client side:
    log4j:WARN Detected problem with connection: java.net.SocketException: Software caused connection abort: socket write error
    and this message on the server:
    Server started...
    Client accepted
    ������������org.apache.log4j.spi.LoggingEven�������������

    Ryan,
    I think if I could log to something common like Microsoft Access it would be a help to me in managing database backups and other things, as Citadel is somewhat unique in its format and methods using the Measurement and Automation Explorer. Maybe I could retrieve data from a 3rd party database back into Citadel if Citadel DB becomes corrupted or lost.
    I don't use ODBC logging now, so please excuse me if I come across as lacking in understanding your request. Could the hypertrend or other objects be programmed to log and/or retrieve data to and/or from the 3rd party ODBC database as well?
    Terry Parks, Engineering Analyst
    Terrebonne Parish Consolidated Government (T.P.C.G.)
    Public Works - Pollution Control

  • Synchronizing peers in transfer over Socket

    Hi again!
    I'm relatively new to Java, so there are many issues I still have to figure out ;-)
    Here are two of them:
    1) How can peers be synchronized in transfer over Socket? For example:
    This is the receiving peer:
    DataInputStream dsin = new DataInputStream(socket.getInputStream());
    String s = dsin.readUTF();This is the sending peer:
    DataOutputStream dsout = new DataOutputStream(socket.getOutputStream());
    dsout.writeUTF("something...");
    dsout.close();At the receiving peer in some cases the EOFException or SocketException (Socket closed) are raised. I suspect this happens either because the receiver tries to read input before it is fully transfered or when the sender already managed to close the socket's OutputStream.
    So how can such a transfer be synchronized?
    2) What if both peers close their socket's OutputStream? Does this result in closing the connection and releasing all its resources, such as port?
    Thank you everyone!

    this is what I learnt:Sorry, try again!
    DO NOT close the Socket on any endpoint until you make sure that the other endpoint managed to call socket.getInputStream().This 'rule' is quite unnecessary.
    According to the documentation, getInputStream() may return a stream which buffer was discarded by network software if a broken connection was detected.That's a complete misreading and misquoting of the documentation. A reset can happen to the connection at any time; can cause loss of data from te socket receive buffer; and has nothing to do with the operation of getting the input stream. Getting the input stream of a socket has nothing to do with the network or the state of the connection. It just constructs a Java object. So this rule is quite pointless.
    Even more, it seems to be a good practice not to close the Socket until you are sure that the other endpoint will not try to read from the channel.You've got that back to front as well. THink about that some more and you will see it involves an infinite regression.
    The only rules you need are these:
    (a) don't close the socket until you're sure the other end has finished writing. You have to close the socket while the other end is still reading, so that it will get a EOS indication, so it will know you've gone away, so it will stop writing and close its end of the socket.
    (b) closing the socket or either of its streams closes the other two items. You should always close the topmost output stream of a socket and nothing else.

  • Change the image resolution through iPhoto

    Does anyone know how to change the image resolution through iPhoto? I know it can be done in other image editing software, but I have yet to find it as an option in iPhoto.

    Hi Rachel,
    There is no option within iPhoto.
    Lori

Maybe you are looking for

  • Which Is The Best Free Video Converter Software?

    Which is the best FREE software for encrypting dvd's for Ipod and which is the best FREE software for converting encrypted dvd videos to my Ipod, or is there out a FREE software that can do both thing?   Windows XP Pro  

  • How can I change the theme of a book?

    I wish to change the template of the book I am working on to another template in my list. Is there a way to do it?

  • XI does not allow me to add new segment....?

    Hi, I created a message from XSD...The XSD allows one node to be repeated say 5 number of times. But when I create the Message out of this XSD, it has just one node for this .Now I want to create another similar node... Any idea how  to do that? Than

  • Cannot print - troubleshooting help

    I am using an oldish pdf generator (header is PDF1.0) and cannot print the document, although it looks fine on-screen The generator embeds full (non-subset) T1 fonts summary: print (to ps file) - fails (in reader) print(to ps file)  as image - fails

  • Org. Unit - Sub org Unit relationship.

    Hi Gurus, I could not see the suborg units under the root org unit when I used the relationship, belongs to. But I could see them when I used the relationship reports to. Which one is the correct relationship between an org unit and a suborg unit? Po