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.

Similar Messages

  • Image transfer using java

    hi,
    i would like to know how to transfer an image from one computer to another in java using sockets.
    please reply if you are willing to help me .
    thank you.
    r.hari haran.

    hi,
    AFAIK thee is no serializable class implementing Image.
    But every image is a 2 dimensional integer array decribing the image pixels. You can write the array to the socket and recreate the image using BufferedImage.
    Gernot

  • Problem w/ image item using 9i BLOB field and InterMedia ORDImage Object

    Hi,dear all,
    I have a problem with image item in Form 6i. Oracle 9i is used as backend DB, and a table contains image data is created for testing:
    create table image_test(
    id number,
    image blob
    In Form 6i, there is no problem to create a block for inserting/updating the image record into the database. However, it can not be used to retrieve image (blob field), the image item remains empty after 'execute query', while the id field can be retrieved. When the same table is created in Oracle 8.1.7, and the exact same form can be used without any problem both in inserting and retrieval. It seems that the Oracle 9i does not use the same way to store BLOB column. Has anybody ever encountered this problem? How to retrieve image (BLOB) in Form 6i from Oracle 9i?
    I tried to use interMedia ORDImage as the data type in Oracle 9i, that is,
    create table image_test(
    id number,
    image ORDSYS.ORDImage
    Same problem, the form can insert record with image, but when retrieving, nothing displayed. Anybody could help! Thanks in advance!

    hi!
    well working with oracle8i and form6i.
    same problem..but i used (instead of blob or clob as datatype..) Long raw..
    it can be saved as usual..i mean Commit..
    and can be retrieved..using Execute_Query..its working fine..
    well if anybody get any other solution..do inform..
    mail_id:
    [email protected]

  • Folder transfer using sockets

    Is there anyway to transfer the whole folder including the subfolders
    using sockets.
    i can transfer the all the files one by one
    but it needs lot of coding like making subfolders in the destination and etc.
    i need to send a folder using a single outputstream
    Thanks
    Ananth

    Ananthakumaran wrote:
    tar and untar will take some time Really? Have you measured that?
    I'll bet if you look, the time it takes is completely dominated by the need to read the files on one side and write the files on the other. Since any copy program has to do the same thing, this should be no slower than any other method.
    and mostly my app is used to transfer large size file
    i need something which can send folder like a single file without any >>> overhead >>>Everything you do has overhead. You want to send files and folders over the network. Using tar to serialize that structure has very little overhead. I doubt the overhead will be visible given the need to actually read and write the files.
    Darren

  • Problem if mail sent using sockets using j2me devices

    Hi,
    I have a strange problem. I am sending a mail using j2me ( using sockets ). The mail will be sent successfully. But when tried to access using pop service, that mail is never seen in the server.
    I sent a mail from j2me device to gmail account - I can see that mail using the gmail login, but using pop service i am not able to see that mail.
    If I send a mail from browser - I can see the mail in both, the browser and also the pop service.
    Can anyone explain what is the problem ?
    Thanks in advance

    Would you be so kind as to edit your original post and add [SOLVED] to the subject?
    Thanks,
    Craig...

  • Problem with image control using more than 1 web cam

    Hi,
    I am using logitech quickcam pro 4000.Actually I want to get image from
    3 web cam at a time wich will act as a CCTV.I want to get picture from
    more than 1 web cam at a time.But,When I start the .vi,than I get image
    from 1 web cam.I have attached the vi and the demonstration file.
    If anyone  has any idea please send me a reply.
    (The code was constructed using information
    from the Logitech Software Development Kit, downloaded from the Logitech web
    site January 4th 2004.  This
    package includes the royalty free distribution with the camera driver.
    To install the package, download and unzip
    LabVIEW Logitech UWA.zip and run Setup.exe in the 'redist' folder.  This installs drivers (if not already
    installed).  Then run LabVIEW and open
    Logitech Image Acquisition Master.vi. 
    Click the LabVIEW run button.
    Notes for Understanding the Code
    [1] The camera is controlled by an Active-X
    reference from a front panel Acitve-X container that displays the pre-view
    image.  To create this, create a blank
    Active-X container on the front panel and select the Active-X Hydra Video
    Portal class.
    [2] Three methods are called, following the
    Visual Basic guide from Logitech.  The
    first establishes a connection to the Active-X server.  The status bar is activated in the preview
    window (EnableUIElements), and we connect a camera (ConnectCamera2).
    [3] Here we set the value of property
    'EnablePreview' to turn on the preview panel.
    [4] We can get the camera description for
    camera zero here (the first camera connected).
    [5] Here we select the video format (64x480
    – can change it later).  The next call
    establishes the preview size by setting property values.  The preview size should be the same as the
    video format for fastest image acquisition.
    [6] We are restricted to saving the picture
    to a BMP file and then reading it in again. 
    This is a limitation of the SDK. 
    After reading the image file we can change it to a JPG if we wish to.
    [7] Here we re-read the image file and
    provide it to ImageDisplay.vi.
    Other methods and property values are
    reasonably self evident.  In LabVIEW, if
    you right click the Active-X reference terminal on any method, you can create a
    new method by simply selecting the appropriate one from a list.  The parameters for the method appear
    automatically and should be reasonably self-evident from the names.  If you want more details, download the SDK
    from Logitech.
    Other methods allow you to make movies in
    real-time or time-lapse sequences.
    Note that you can also monitor Active-X
    events to detect inputs or parameter changes made elsewhere.  For example it is possible to detect when
    the button on the camera is pressed.)
    Thanks
    Kabir
    Kabir mamun
    PhD Student,DCU
    [email protected]
    www.iward2010.blogspot.com
    Attachments:
    Logitech Image Acquisition Master.vi ‏98 KB

    Hi Peter,
    Thanks for your e-mail.And sorry for late.
    I have changed my activex server in my labview programme.Current 
    server name is XVideoOCX.I have attached 1 example.Still I am facing
    the same problem that I am not getting disply from more than 1 web
    cam.So would you be able to advice me,what should I do regarding this
    matter.
    Actually,This is a part  of my M.Sc project.I am under pressure.Peter,Please do me  this fevour.
    Thanks
    Kabir
    1 eample from help file:
    Video Disply
    1. Choose the input mode (Video, Single Image Files, Screen, etc.)
    XSetInputMode(0) // This
    chooses video as input
    2. Choose the video device
    XSetVideoInput(0) //
    Choose the first available video input device
    3. Initialize XVideoOCX
    XInit() // Initialize
    XVideoOCX
    4. Start internal video capture
    XStart()
    now XVideoOCX should display the live video
    5. Stop internal video capture
    XStop()
    6. Close XVideoOCX
    XClose()
    Kabir mamun
    PhD Student,DCU
    [email protected]
    www.iward2010.blogspot.com
    Attachments:
    ax2.vi ‏23 KB

  • Problems showing image file using ShowProperty servlet

    Hi there,
    I´m having problems trying to show an image from the repository using ShowProperty servlet. My node is of type image and my repository is a Library Services enabled repository. When I try to show my node´s binary property "file" the servlet returns the following message "A Primary Property is not defined for Node:...". But checking the node´s ObjectClass I can see that the file property is defined as a primary property. Can somebody help me on this ?
    tks,
    George Earp

    Hi Anders,
    first thanks for trying to help me. Answering your questions in order: I certified myself that the node was saved and checked in using the Portal Administration site. I looked in debug mode and the Node is loaded correctly but the properties aren´t there. I have some more information for you. I decompiled the servlets (ShowBinaryServlet and ShowPropertyServlet). The news are that ShowBinaryServlet is a ShowPropertyServlet´s child that has no additional implementation. Other relevant information is that ShowPropertyServlet implementation gets the Node throught NodeOps object and try to get the binary property with it. But, reading the API and doing tests I could only get my Node properties throught a Virtual Node (see NodeOps Interface part of the API). That´s because my Repository is a managed repository. So, the servlets can´t find the bynary property in my Node because it isn´t there... It is under a VirtualNode... Am I right ? If that´s true I believe I´ll have to implement a solution myself... Too sad... :(
    Message was edited by eduardo.earp at Jan 25, 2005 9:21 AM

  • 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;

  • Inconsistency problem with Image preview using ImageServlet -JSP

    I have a Servlet that reads Images ( JPG) from file system and sends bites to response,
    Code works fine and I can see the Image, Problem is that it is very Inconsistent sometimes I can see image and sometimes I see the red X mark instead of image,
    if I refresh the page wih shift key holding, the image shows up.
    when the image was obsent I can right click the image and go to properties and see the image path and it was correct.
    any one has similar experiences with Images before ?
    Servlet code follows.
    File f = new File(imgPath);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
    // Set all the required header information
    response.setContentType("image/gif");
    response.setContentLength((int)f.length());
    response.reset();
    response.resetBuffer();
    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    byte[] buf = new byte[1024];
    int nRead;
    while( (nRead=in.read(buf)) != -1 ){
          out.write(buf,0,nRead);
    / Close up all our resources
    out.flush();
    in.close();
    response.flushBuffer();JSP code in pieces.
    <% response.setHeader("Cache-Control","no-cache");
       response.setDateHeader("Expires", -1);
       response.setHeader("Pragma", "no-cache");
       response.addHeader("Cache-control", "no-store");
       response.addHeader("Cache-control", "max-age=0");
    %>
    <html:html>
    <head>
    <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
    </head>
    <body>
    <img src="<%=request.getContextPath()%>/imageServlet?imgType=badge&imgName=<bean:write name='badge' property='name'/>" width="136" height="136" alt="" border="0">
    </body>
    <head> <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> </head>
    </html:html>Thanks
    Narendra

    Hi Peter,
    Thanks for your e-mail.And sorry for late.
    I have changed my activex server in my labview programme.Current 
    server name is XVideoOCX.I have attached 1 example.Still I am facing
    the same problem that I am not getting disply from more than 1 web
    cam.So would you be able to advice me,what should I do regarding this
    matter.
    Actually,This is a part  of my M.Sc project.I am under pressure.Peter,Please do me  this fevour.
    Thanks
    Kabir
    1 eample from help file:
    Video Disply
    1. Choose the input mode (Video, Single Image Files, Screen, etc.)
    XSetInputMode(0) // This
    chooses video as input
    2. Choose the video device
    XSetVideoInput(0) //
    Choose the first available video input device
    3. Initialize XVideoOCX
    XInit() // Initialize
    XVideoOCX
    4. Start internal video capture
    XStart()
    now XVideoOCX should display the live video
    5. Stop internal video capture
    XStop()
    6. Close XVideoOCX
    XClose()
    Kabir mamun
    PhD Student,DCU
    [email protected]
    www.iward2010.blogspot.com
    Attachments:
    ax2.vi ‏23 KB

  • Problem seeing images using Firefox

    I have a problem seeing images when using Firefox. I can see them at first, but when i scroll down they dissappear until I get to a certain point on the screen (like when the images are at the top of the firefox screen) then I can see them. Was wondering if anyone knew what the problem could be?

    from the system details you've submitted it appears that you have the foxit reader pdf plugin on your system - it's known to cause problems with hotmail since firefox 12. disable it in firefox > addons > plugins until there's an update by foxit which fixes the issue

  • Image Transfer Nokia 6680

    Hi,
    I am using the latest version of Nokia PC Suite (6.80.22), in combination with windows XP, SP 2.
    Image transfer used to work fine, until approx 2 or 3 months ago. Since then, PC suite does not identify new pictures anymore. I have tried reinstalling and installing newer versions, but this did not help.
    I can however transfer the videos to my computer, but for some strange reason, I can not transfer any picture at all.
    I have the problem when I am using a cable or using bluetooth (havent tried IR).
    Does anybody know a possible solution for this problem?
    Looking forward to a reply!
    Julian

    Hi,
    Does this happen with all kind of image files (e.g *.jpg or *.gif ) ?
    If you change the image file extension to video extension in phone, can you then transfer that tp PC??
    Does Nokia Image Store application transfer those image files to PC?

  • Send html page (with images) using sockets

    I am trying to implement http and am coding this using sockets. So it is a simple client-server set up where the browser queries my server for a webpage and it should be shown. The html itself is fine, but I can't get any of the images to show up! All of my messages give me a status "200 OK" for the images, so I cant understand what my problem is!
    Also, is the status and header lines supposed to be shown in the browser? I didnt think so but it keeps showing up when I query a webpage.
    Please help!
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class WebServer
         public static void main(String argv[]) throws Exception
              // Set the port number.
              int port = 8888;
              // Establish the listen socket.
              ServerSocket ssocket = new ServerSocket(port);
              // Establish client socket
              Socket csocket = null;
              // Process HTTP service requests in an infinite loop.
              while (true)
                   // Listen for a TCP connection request.
                   // (note: this blocks until connection is made)
                   csocket = ssocket.accept();     
                   // Construct an object to process the HTTP request message.
                   HttpRequest request = new HttpRequest(csocket);
                   // Create a new thread to process the request.
                   Thread thread = new Thread(request);
                   // Start the thread.
                   thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
         // Implement the run() method of the Runnable interface.
         public void run()
              try
                   processRequest();
              catch (Exception e)
                   System.out.println(e);
         private static void sendBytes(FileInputStream fis, OutputStream os)
         throws Exception
            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] buffer = new byte[1024];
            int bytes = 0;
           // Copy requested file into the socket's output stream.
           while((bytes = fis.read(buffer)) != -1 ) {
              os.write(buffer, 0, bytes);
              os.flush();
         private static String contentType(String fileName)
              fileName = fileName.toLowerCase();
              if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
                   return "text/html";
              if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ) {
                   return "image/jpeg";
              if(fileName.endsWith(".gif")) {
                   return "image/gif";
              return "application/octet-stream";
         private void processRequest() throws Exception
              // Get a reference to the socket's input and output streams.
              InputStream is = socket.getInputStream();
              DataOutputStream os = new DataOutputStream(socket.getOutputStream());
              // Set up input stream filters.
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              // Get the request line of the HTTP request message.
              String requestLine = br.readLine();
              // Display the request line.
              System.out.println();
              System.out.println(requestLine);
              // Get and display the header lines.
              String headerLine = null;
              while ((headerLine = br.readLine()).length() != 0)
                   System.out.println(headerLine);
              // Extract the filename from the request line.
              StringTokenizer tokens = new StringTokenizer(requestLine);
              tokens.nextToken();  // skip over the method, which should be "GET"
              String fileName = tokens.nextToken();
              // Prepend a "." so that file request is within the current directory.
              fileName = "C:\\CSM\\Networking\\Project1" + fileName;
              // Open the requested file.
              FileInputStream fis = null;
              boolean fileExists = true;
              try {
                   fis = new FileInputStream(fileName);
              } catch (FileNotFoundException e) {
              fileExists = false;
              // Construct the response message.
              String statusLine = null;
              String contentTypeLine = null;
              String entityBody = null;
              if (fileExists) {
              statusLine = "200 OK" + CRLF;
              contentTypeLine = "Content-type: " +
                   contentType( fileName ) + CRLF
                   + "Content-length: " + fis.available() + CRLF;
              else {
              statusLine = "404 Not Found" + CRLF;
              contentTypeLine = "Content-type: text/html" + CRLF;
              entityBody = "<HTML>" +
                   "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
                   "<BODY>Not Found</BODY></HTML>";
              // Send the status line.
              os.writeBytes(statusLine);
              System.out.println(statusLine);
              // Send the content type line.
              os.writeBytes(contentTypeLine);
              System.out.println(contentTypeLine);
              // Send a blank line to indicate the end of the header lines.
              os.writeBytes(CRLF);
              // Send the entity body.
              if (fileExists)     
                   sendBytes(fis, os);
                   fis.close();
              // file does not exist
                     else
                   os.writeBytes(entityBody);
              // Close streams and socket.
              os.flush();
              os.close();
              br.close();
              socket.close();
    }

    ok. i figured it out. STUPID mistake. i forgot to include "HTTP/1.1" in my status line!!!

  • File transfer using non-blocking sockets - data mysteriously  vanish

    Hello,
    I need to pass some big amount of data using sockets. I my appliaction I have noticed that sometimes I didn't get all bytes. To check it out I wrote simple client + server to figure out what is happening. So:
    - I have a sender and receiver application
    - I'm trying to transfer 5MB text file.
    - On receiver side, output file is never larget than 3MB
    - If I put some timeout on sender side (1ms timeout between write operations) everything works fine.
    Could someone tell me what I do wrong? Why data disappears and when? The same file transfered using old sockets goes always fine...
    Thanks in advance!
    Here is complete source for receiver and sender:
    RECEIVER:
    import java.io.FileOutputStream;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    public class ReceiverA {
          * @param args
         public static void main(String[] args) {
              String outputFile = "c:\\outputA.txt", host = "127.0.0.1";          
              int port = 8001, bufferSize = 10240;
              try {
                   ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
                   Selector selector = Selector.open();
                   ServerSocketChannel server = ServerSocketChannel.open();
                   server.configureBlocking(false);
                   server.socket().bind(new InetSocketAddress(host, port));
                   server.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Server started");
                   while(true)
                        selector.select();
                        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                        while (iterator.hasNext()) {
                             SelectionKey key = (SelectionKey) iterator.next();
                             iterator.remove();
                             if (key.isAcceptable()) {                              
                                  SocketChannel client = server.accept();
                                  client.configureBlocking(false);
                                  client.register(selector, SelectionKey.OP_READ);                              
                                  continue;
                             SocketChannel channel = (SocketChannel) key.channel();
                             int counter = 1;
                             if ( key.isReadable() ) {
                                  FileOutputStream os = new FileOutputStream(outputFile);
                                  int res;
                                  do
                                       buffer.clear();
                                       res = channel.read(buffer);
                                       counter += res;
                                       System.out.println(res);
                                       buffer.flip();
                                       os.write(buffer.array(), 0, buffer.limit());
                                  while( res >= 0 );          
                                  channel.close();
                                  os.close();          
                                  System.out.println("Receiver: " + counter);
                                  return;
              } catch (Exception e) {
                   e.printStackTrace();
    }SENDER:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    public class SenderA {
         public static void main(String[] args) {
              String inputFile = "c:\\inputA.txt" , host = "127.0.0.1";          
              int port = 8001, bufferSize = 10240;
              try {
                   ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
                   byte[] byteArr = new byte[buffer.capacity()];
                   Selector selector = Selector.open();
                   SocketChannel connectionClient = SocketChannel.open();     
                   connectionClient.configureBlocking(false);
                   connectionClient.connect(new InetSocketAddress(host, port));
                   connectionClient.register(selector, SelectionKey.OP_CONNECT);
                   while(true) {
                        selector.select();
                        Iterator<SelectionKey> iterator = selector.selectedKeys()
                                  .iterator();
                        while (iterator.hasNext()) {
                             SelectionKey key = (SelectionKey) iterator.next();
                             iterator.remove();
                             SocketChannel client = (SocketChannel) key.channel();
                             if (key.isConnectable()) {
                                  if (client.isConnectionPending()) {
                                       System.out.println("Trying to finish connection");
                                       try {
                                            client.finishConnect();
                                       } catch (IOException e) {
                                            e.printStackTrace();
                                  client.register(selector, SelectionKey.OP_WRITE);
                                  continue;
                             if(key.isWritable()) {
                                  FileInputStream is = new FileInputStream(inputFile);
                                  int res;
                                  int counter = 0;
                                  do
                                       buffer.clear();
                                       res = is.read(byteArr, 0, byteArr.length);                                   
                                       System.out.println(res);
                                       if ( res == -1 ) break;
                                       counter += res;
                                       buffer.put(byteArr, 0, Math.min(res, buffer.limit()));
                                       buffer.flip();
                                       client.write(buffer);
                                        * When I remove comment file transfer goes OK!
                                       //Thread.sleep(1);
                                  while( res != -1 );          
                                  client.close();
                                  is.close();          
                                  System.out.println("Receiver: " + counter);
                                  return;
              catch(Exception e) {
                   e.printStackTrace();
    }

    There are at least two problems here.
    A. In the receiver you should test for -1 from the read() immediately, rather than continue with the loop and try to write -1 bytes to the file.
    B. In the sender you are ignoring the return value of client.write(), which can be anything from 0 to the buffer length. If you get 0 you should wait for another OP_WRITE to trigger; if you get a 'short write' you need to retry it until you've got nothing left to write from the current buffer, before you read any more data. This is where the data is vanishing.

  • Sending an image using sockets

    can anybody give an idea about how to send an image using sockets.....
    what i want to do is a client that connects to a server this server has the images...so the client request any image that the server has and display it int the client's frame

    Very good point! The problem ( I told you it was untested!) with the above is that the Image class isn't actually serialisable.
    The solution depends on how you're storing your images and how you're managing them within your server. It also depends on your proposed client. For example, if your client was a browser and your images files on a disk, then you might use:
                        Socket s;
                        // Write out header
                        PrintWriter pw = new PrintWriter(s.getOutputStream());
                        pw.println("Content-Type: image/gif");
                        // And send out data.
                        byte[] buffer = new byte[2048];
                        int count;
                        while((count = fis.read(buffer))>0) {
                             s.getOutputStream().write(buffer, 0, count);
                        s.getOutputStream().close();
                   }although you'd probably be better off using a proper webserver. If you're using a proprietry client, then you can either use Swing's JEditorPane to act like browser and display the image as the server above presents it.
    Otherwise, your client could use the incoming byte stream to create a BufferedImage instance.
    How are you storing your images and how are you presenting them?

  • 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.

Maybe you are looking for

  • System lock ups / cannot start system

    Hello, I am using Slimline S5648HK. I have been using the PC for over a year and a half now, and  recently I am having trouble with the PC locking up / weird screen (Some fuzzy colors) and it auto reboot. In most cases, it occures when watching video

  • PO Approval based on Vendor Category.

    Hi There is a typical scenario in my client's system. Now we need to implement SAP PO approval process is there. There are two major characteristics 1. PO value 2. Vendor's present category. Vendor's present grade : During vendor evaluation, vendor a

  • Too late to buy warranty?

    Just bought a Dell Studio MT Desktop Q8200 November 30 (3 days ago). I did not buy an  extended warranty at the time. I wasn't aware of the arrangement Dell had w/Best Buy about warranties until today and I would like to buy a extended warranty now.

  • 0008 error

    Hi, I am saving the 0008 infotye i m getting the entry in table T510 for the key 40 013 on 29.02.2008. Pls  let me know on this. Thanks and Regards, Revathi.

  • OOP, constructors. Why is the object null?

    Hi. Here's AS3 behavior that I don't quite understand. The code is: public class TestA       public var data:Object;       public function TestA()            trace("From A", this.data); public class TestB extends TestA      public function TestB()