Compressed objects over socket

The simplest example on a tutorial http://java.sun.com/developer/technicalArticles/Programming/compression/ does work:
// write to client
GZIPOutputStream gzipout = new
  GZIPOutputStream(socket.getOutputStream());
ObjectOutputStream oos = new
  ObjectOutputStream(gzipout);
oos.writeObject(obj);
gzipout.finish();However, what shoul be the correct way for sending/receiving multiple objects in a socket write/read loop?
Here's an SSCCE that fails with every conceivable tweak, conceived by my weak brain.
/* server */
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class LoopServer{
  public static void main(String[] args) throws Exception{
    ServerSocket ss = new ServerSocket(9999);
    Socket cs = ss.accept();
    System.out.println("client accepted");
    GZIPOutputStream gos =  new GZIPOutputStream(cs.getOutputStream());
    ObjectOutputStream oos = new ObjectOutputStream(gos);
    ObjectInputStream ois
      = new ObjectInputStream(new GZIPInputStream(cs.getInputStream()));
    int count = 0;
System.out.println("begin loop"); // never comes here
    while (++count < 30){
      oos.writeObject(new Date());
      gos.finish();
      oos.flush();
      System.out.println((Date)(ois.readObject()));
    cs.close();
/* client */
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class LoopClient{
  public static void main(String[] args) throws Exception{
    Socket cs = new Socket("localhost", 9999);
    GZIPOutputStream gos =  new GZIPOutputStream(cs.getOutputStream());
    ObjectOutputStream oos = new ObjectOutputStream(gos);
    ObjectInputStream ois
      = new ObjectInputStream(new GZIPInputStream(cs.getInputStream()));
      System.out.println((Date)(ois.readObject()));
    int count = 0;
System.out.println("begin loop"); // never comes here
    while (++count < 30){
      System.out.println((Date)(ois.readObject()));
      oos.writeObject(new Date());
      gos.finish();
      oos.flush();
    cs.close();
}

ejp wrote:
Isn't there a way to prevent that? Not unless you write a subclass of OOS which breaks the rules for writing finalizers, which you don't want to do either ...OK. I think I have come up with a sound hack that can avert the finalizer risk of socket closing.
According to another thread:
http://forum.java.sun.com/thread.jspa?threadID=5274508
Ejp's recommended method did work for receiving a single byte array while my method which uses ByteArrayOutputStream and its toByteArray() didn't.
Question: When the sender has sent a single byte array at a burst, should the receiver not use fragmentary read() or read(byte[smallsize])?. Should the receiver only use read(byte[fullsize])? If the answer is yes, then it would explain the cause of the above 'didn't work' failure.
/* server */
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class LoopServer5{
  public static void main(String[] args) throws Exception{
    OutputStream os;
    InputStream is;
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais;
    GZIPOutputStream gos;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    DataOutputStream dos;
    DataInputStream dis;
    ServerSocket ss = new ServerSocket(9999);
    Socket cs = ss.accept();
    System.out.println("client accepted");
    os = cs.getOutputStream();
    is = cs.getInputStream();
    dos = new DataOutputStream(os);
    dis = new DataInputStream(is);
    int count = 0;
    int d;
    while (++count <= 10){
      /* in order to avert using multiple disposable OOS
       * wrapping a GOS wrapping the Socket OS in turn,
       * the Socket OS simply send a byte array as a DOS
       * thereby averting the risk of Socket OS finalization
      baos = new ByteArrayOutputStream();
      gos = new GZIPOutputStream(baos);
      oos = new ObjectOutputStream(gos);
      oos.writeObject(new Date());
      gos.finish();
      oos.close();
      byte[] ba = baos.toByteArray();
      dos.writeInt(ba.length); // ejp's recommended way of doing things  marked #
      dos.write(ba);                // #
      dos.flush();                    // #
      int size = dis.readInt();  // #
      byte[] buf = new byte[size]; // #
      dis.readFully(buf); // # simply read a byte array, not an Object
      bais = new ByteArrayInputStream(buf);
      // create an OIS from the byte array received
      // what a clever hack! ...self-praise!
      ois = new ObjectInputStream(new GZIPInputStream(bais));
      System.out.println
        ("from client: " + (Date)(ois.readObject()) + " " + count);
    cs.close();
/* client */
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class LoopClient5{
  public static void main(String[] args) throws Exception{
    OutputStream os;
    InputStream is;
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais;
    GZIPOutputStream gos;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    DataOutputStream dos;
    DataInputStream dis;
    Socket cs = new Socket("localhost", 9999);
    os = cs.getOutputStream();
    is = cs.getInputStream();
    dos = new DataOutputStream(os);
    dis = new DataInputStream(is);
    int count = 0;
    int d;
    while (++count <= 10){
      int size = dis.readInt();
      byte[] buf = new byte[size];
      dis.readFully(buf);
      bais = new ByteArrayInputStream(buf);
      ois = new ObjectInputStream(new GZIPInputStream(bais));
      System.out.println
        ("from server: " + (Date)(ois.readObject()) + " " + count);
      baos = new ByteArrayOutputStream();
      gos = new GZIPOutputStream(baos);
      oos = new ObjectOutputStream(gos);
      oos.writeObject(new Date());
      gos.finish();
      oos.close();
      byte[] ba = baos.toByteArray();
      dos.writeInt(ba.length);
      dos.write(ba);
      dos.flush();
    cs.close();
}  

Similar Messages

  • URGENT : Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?. Should i use RMI or Externalize?. Any help would be appreciated.

    {snip}
    Like this:
    public class SerializableLibraryClass extends
    LibraryClass implements Serializable {
    }Then you've got a class that is exactly the same as
    LibraryClass, but is now serializable.Not quite. The base class still isn't Serializable. Take, for example, the following code:
    public class A
        public int a1;
    public class B extends A implements Serializable
        public int b1;
    B beforeSend = new B();
    beforeSend.a1 = 1;
    beforeSend.b1 = 2;
    objectOutputStream.writeObject(b);
    B afterSend = (B)(objectInputStream.readObject());Both beforeSend and afterSend have fields a1 and b1. For beforeSend, a1 = 1 and b1 = 2. For afterSend, b1 = 2 but a1 = 0. The superclass wasn't Serializable; therefore, its members weren't Serialized and, when the object was created on the other side of the stream, a1 was left at its initial value.
    In short, you can't just Serialize the subclass. That Serialization won't apply to its superclasses.

  • Pass non-serializable objects over sockets

    I am working with a non-serializable class.I can't change it to serializable(since it's an API class).I can't create a subclass either as I need to pass the same exact Object .I have tried wrapping it in a serializable class (as transient )but then the particular object that I need is not serialized.Is there a way to pass non-serializable objects over sockets?.Some other way of doing this?.

    Have you considered leaving it in situ and using RMI to manipulate it remotely ?
    To be a little pedantic, if you need the "same exact object" then there's no technique that will work for you, since you can only copy an object between JVMs, not move it.
    D.

  • Sending object over socket - please help (urgent)

    I have written a server/client application where server sends object to client.
    But on the client I've received the first message "@Line 1: Get ready!!!" TWICE but NEVER the second message "@Line 2: Please input Start".
    Please help me! Its urgent! I appreciate my much in advance.
    The source for Server:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import sendNode;
    public class TestSer {
         static sendNode sendNodeObj = new sendNode();
    static String inputLine;
         public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try {
    serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
    System.err.println("Could not listen on port: 4444.");
    System.exit(1);
    Socket clientSocket = null;
    try {
    clientSocket = serverSocket.accept();
    } catch (IOException e) {
    System.err.println("Accept failed.");
    System.exit(1);
    OutputStream o = clientSocket.getOutputStream();
    ObjectOutput out=new ObjectOutputStream(o);
    BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        clientSocket.getInputStream()));
    sendNodeObj.sendMsg="@Line 1: Get ready!!!";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    sendNodeObj.sendMsg="@Line 2: Please input Start";
    sendNodeObj.typeNode=-2;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    while (!inputLine.equalsIgnoreCase("Start")) {
         sendNodeObj.sendMsg="@Error, Please input Start";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();
    The source code for Client :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.applet.Applet;
    import sendNode;
    public class TestCli extends Applet {
    static sendNode recNodeObj=null;
    public static void main(String[] args) throws IOException {
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    Socket kkSocket = null;
    PrintWriter out = null;
    try {
    kkSocket = new Socket("127.0.0.1", 4444);
    out = new PrintWriter(kkSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    System.err.println("Don't know about host.");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to: taranis.");
    System.exit(1);
    InputStream i= kkSocket.getInputStream();
    ObjectInput in= new ObjectInputStream(i);
    try {
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
    if (recNodeObj.sendMsg.equalsIgnoreCase("@Line 2: Please input Start")) {
    out.println("Start");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    System.out.println("receive error.");
    System.exit(1);
    out.close();
    in.close();
    stdIn.close();
    kkSocket.close();
    The object to be sent:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class sendNode implements Serializable {
    String sendMsg;
    int typeNode; // -1 no ObjectNode;
    // 1 right node, 2 base node, 3 left node;
    Object objectNode;

    You forgot to reset the OOS. ObjetOutputStream keeps a buffer of objects, so if you write the same object again with changes on it, you must reset the buffer.
    out.writeObject(sendNodeObj);
    out.flush();
    out.reset();

  • Sending objects over sockets - issues i am having

    Hi, this is my first time posting on these forums and I have exhausted my mental capacity on this problem i have been having the past few days. Hopefully somone could help me out.
    I am doing a uni project, and the goal i am currently trying to achieve is to send an object (serialized) from a client to a server. I will atach the code i have written and i will explain more from there.
    This is the server (part of the class, which calls this method)
    Constructor:
      public Broker(String bID) throws Exception {
        brokerID = bID;
        bServer = new ServerSocket(Integer.parseInt(bID));
        System.out.println("Broker listening on port " + bID);
        this.start();
    Main method
      public static void main(String[] args) throws Exception {
        new Broker("8008");
    run method
      public void run() {
        while(true) {
          try {
            Socket bSocket = bServer.accept();
            System.out.println("Accepted a connection from: " + bSocket.getInetAddress());
            brokerServer(bSocket);
            bSocket.close();
            System.out.println("Connection closed");
          catch (Exception e) { e.printStackTrace(); }
    Broker Server
      public void brokerServer(Socket bSocket) {
        BufferedReader in = null;
        ObjectOutputStream oos = null;
        PrintWriter out = null;
        ObjectInputStream ois = null;
        try {
          while (true) {
            oos = new ObjectOutputStream(new DataOutputStream(bSocket.getOutputStream()));
            out = new PrintWriter(new OutputStreamWriter(bSocket.getOutputStream()));
            ois = new ObjectInputStream(bSocket.getInputStream());
            in = new BufferedReader(new InputStreamReader(bSocket.getInputStream()));
            out.println("Connection with Broker on port " + brokerID + " established");
            out.flush();
            //read in first line
            String str = in.readLine();
            //if lineis null, break while loop
            if (str == null)  break;
            else {
              //a request is recieved from user to get user certificate
              if (str.trim().equals("GETUSERCERT")) {
                //read in the userName, size of paywords and user publick key (used in certificate)
                String userName = in.readLine();
                String size = in.readLine();
                PublicKey userPk = (PublicKey) ois.readObject();
                //generate user certificate
                UserCertificate uc = generateUserCertificate(userName, userPk, Integer.parseInt(size, 10));
                //send text to user stating next message is user certififcate
                out.println("SENDUSERCERT");
                out.flush();
                //user Certificate
                oos.writeObject( (UserCertificate) uc);
                oos.flush();
                break;
              if (str.trim().equals("FINISH"))
                break;
            ois.close();
            oos.close();
            out.close();
            in.close();
        catch(Exception e) { e.printStackTrace(); }
    This is the client
      private void requestUserCertificate(int sizeOfPaywordChain, String BrokerID) {
        String host = "localhost";
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        PrintWriter out = null;
        BufferedReader in = null;
        Socket u2bSocket = null;
        try {
          u2bSocket = new Socket(host, Integer.parseInt(BrokerID));
          System.out.println("Connecting to Broker on port " + BrokerID);
          ois = new ObjectInputStream(new DataInputStream(u2bSocket.getInputStream()));
          oos = new ObjectOutputStream(u2bSocket.getOutputStream());
          out = new PrintWriter(new OutputStreamWriter(u2bSocket.getOutputStream()));
          in = new BufferedReader(new InputStreamReader(u2bSocket.getInputStream()));
          //Informs broker that a user certificate is being requested
          out.println("GETUSERCERT");
          //send to broker, username and size of payword chain
          out.println(userName);
          out.println(sizeOfPaywordChain);
          out.flush();
          //send user's public key accross
          oos.writeObject((PublicKey) userPublicKey);
          oos.flush();
          out.println("FINISH");
          out.flush();
          //wait for response
          while(true) {
            //read in line
            String str = in.readLine();
            //if line is null, break while loop
            if (str == null) break;
            //if line read is "SENDUSERCERT" then next line is userCertificate sent from Broker
            if (str.trim().equals("SENDUSERCERT")) {
              //read User Certificate
              userCert = (UserCertificate)ois.readObject();
              break;
            else System.out.println(str);
          //close connections and streams
          u2bSocket.close();
          ois.close();
          oos.close();
          out.close();
          in.close();
        catch (Exception e) { e.printStackTrace(); }
      }I will be regurarly checking this thread, so any other code which you think i should post i will, i can post is ASAP.
    The problem
    First time i run the programs, it works perfectly, however when i run the client program again, it shows this error
    java.io.EOFException
         at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2438)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1245)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
         at User.requestUserCertificate(User.java:75)
         at User.main(User.java:278)the broker server doesn't display anything.
    Would anyone have any idea whats going on??
    Sometimes when i run it, it might display the above error, or it might work. its about 50/50. I have read heaps of similar problems people have had and posted on this forum, but i still don't have any luck in solving this delema.
    Any kind of help will be greatly appreciated.
    Rish

    I see one problem with the code. You are opening both ObjectInputStream ois and a BufferedReader in on the same socket. This won't work as "in" will read ahead to fill up its buffer. This could cause "ois" to find the socket already at end of stream prematurely. I would only use the Object Streams and send the strings as objects.

  • How do I write objects over a SocketChannel?

    Using the regular Socket class we can pass objects over sockets like this.
    Socket s = new Socket("127.0.0.1", 80);
    ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
    out.writeObject(new Object());
    Now, I've looked through the documentation on the new Channel classes and have only seen ways to pass bytes over the channel, not an entire object. Is there an easy way to pass an entire object over a channel? Am I just missing an appropriate wrapper that adds this functionality?
    Thanks,
    Dave

    This code will help you converting an Object to a byte[]:
    //Object to send MUST implement Serializable
    SerializedObject anObject = new SerializedObject();
    //byte[] needed to send
    byte[] aByteArray = null;
    //the conversion
    java.io.ByteArrayOutputStream aByteArrayOutputStream = new java.io.ByteArrayOutputStream();
    java.io.ObjectOutputStream aObjectOutputStream = new java.io.ObjectOutputStream(aByteArrayOutputStream);
    aObjectOutputStream.writeObject(anObject);
    aObjectOutputStream.close();
    aByteArray = aByteArrayOutputStream.toByteArray();
    //When you receive the Object you should reverse the conversion
    //byte[] reveived from InputStream
    byte[] aReceivedByteArray;
    //Expected Object
    SerializedObject theExpectedObject = null;
    //the conversion
    java.io.ByteArrayInputStream aByteArrayInputStream = new java.io.ByteArrayInputStream(aReceivedByteArray);
    java.io.ObjectInputStream aObjectInputStream = new java.io.ObjectInputStream(aByteArrayInputStream);
    theExpectedObject = aObjectInputStream.readObject();
    That's one way to do it.
    You should watch out with Serializable object when sending it to another OS or JRE-version.

  • Objectserialization with gzip over socket

    Hi,
    I'm trying to serialize and GZIP objects over a socket but it does not seem to work i both directions on the same socket!? I works fine if the client sends a serialized/compressed object to the server and then exits. If the client wants to read back an answer from the server on the same socket the client hangs when it tries to create the ObjectInputStream!? Please look at the example below:
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.GZIPOutputStream;
    public class GZIPTest
      public GZIPTest()
        new Server().start();
        new Client().start();
      class Client extends Thread
        public void run()
          try
            setName("Client");
            Socket s = new Socket("127.0.0.1", 2222);
            System.out.println("["+getName()+"]creating outputstream...");
            GZIPOutputStream gzipOut = new GZIPOutputStream(s.getOutputStream());
            ObjectOutputStream out = new ObjectOutputStream(gzipOut);
            System.out.println("["+getName()+"]writing object");
            out.writeObject(new String("Hi!"));
            gzipOut.flush();
            out.flush();       
            System.out.println("["+getName()+"]creating gzipinputstream...");
            GZIPInputStream gzipIn = new GZIPInputStream(s.getInputStream());       
            System.out.println("["+getName()+"]done!");
            System.out.println("["+getName()+"]creating objectinputstream...");
            //here it hangs...?
            ObjectInputStream in = new ObjectInputStream(gzipIn);
            //try to read answer from server
            String result = (String)in.readObject();
            System.out.println("["+getName()+"]from server: " + result);
            out.close();
            in.close();
            s.close();
          catch(Exception e)
            System.out.println("["+getName()+"]Boom!");
            e.printStackTrace();
      class Server extends Thread
        public void run()
          try
            setName("Server");
            ServerSocket ss = new ServerSocket(2222);
            Socket s = ss.accept();
            System.out.println("["+getName()+"]client accepted!");
            GZIPOutputStream gzipOut = new GZIPOutputStream(s.getOutputStream());
            ObjectOutputStream out = new ObjectOutputStream(gzipOut);
            GZIPInputStream gzipIn = new GZIPInputStream(s.getInputStream());
            ObjectInputStream in = new ObjectInputStream(gzipIn);
            String mess = (String)in.readObject();
            System.out.println("["+getName()+"]from client: " + mess);
            out.writeObject(new String("you said: " + mess));
            out.flush();
            in.close();
            out.close();
            s.close();       
          catch(Exception e)
            System.out.println("["+getName()+"]Boom!");
            e.printStackTrace();
      public static void main(String[] args)
        new GZIPTest();
    }Any help appreciated!
    regards

    Hi,
    I'm trying to serialize and GZIP objects over a
    socket but it does not seem to work i both directions
    on the same socket!? I works fine if the client sends
    a serialized/compressed object to the server and then
    exits. If the client wants to read back an answer
    from the server on the same socket the client hangs
    when it tries to create the ObjectInputStream!?
    Please look at the example below:CTRL-BREAK will show you a thread dump of the hung program.
    ==========================
    "Client" prio=6 tid=0x0ada7000 nid=0xe74 runnable [0x0b00f000..0x0b00fd14]
    java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at GZipTest$Client.run(GZipTest.java:41)
    "Server" prio=6 tid=0x0aadf800 nid=0xbc4 runnable [0x0afaf000..0x0afafd94]
    java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at GZipTest$Server.run(GZipTest.java:72)
    ============================
    Both threads are blocked waiting to read from the socket.
    If you read the docs for the ObjectInputStream constructor you will find:
    =======================
    Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified.
    This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
    =======================
    So, clearly something isn't allowing the stream to flush the header for the Object. If you remove the GZIP streams, things work as expected. Reading the docs for DeflaterOutputStream, from which GZIPOutputStream inherits,
    you will find the following method:
    =============
    public void finish()
                throws IOExceptionFinishes writing compressed data to the output stream without closing the underlying stream.
    Use this method when applying multiple filters in succession to the same output stream.
    Throws:
    IOException - if an I/O error has occurred
    ====================
    When you've finished writing the object, call finish on the compressed stream.
    Jim S.

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

  • Send XML over Sockets

    I am beginning and I need to send XML formatted data from Swing Client to Server for parsing/processing/and response.
    There are no web server available to use. I think its best to use socket connection, but how do I send xml data over socket, and how do I receive it from server and parse it?
    I have read and cannot find a similar example.

    Xerces has DOMSerializer which can be used to serialize a Document object to a string. Once it's a string it's trivial to transmit over a socket connection. On the other side, to parse it, you'll have to create a StringReader for the received string and then an InputSource from the StringReader. You'll then be able to pass the InputSource to the DocumentBuilder.parse( ) method to generate a Document on the receiving side.
    Hope that helps,
    - Jesse

  • Image over sockets

    Hello,
    What I'm basically trying to do is to send an Image among strings over sockets.
    I have a serializable object and I'm sending back and forth. In this object I have an ImageIcon but when I try to send it to the client I'm getting the following error on the server-side:
    failed to load image contents
    java.io.IOException: failed to load image contents
    at javax.swing.ImageIcon.writeObject(ImageIcon.java:418)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:890)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1333)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:291)
    at ThreadedDataObjectHandler.run(ThreadedDataObjectServer.java:90)
    line 90: out.writeObject(myObject); // myObject is the serializable objectout is:
    ObjectOutputStream out=new ObjectOutputStream(incoming.getOutputStream()); any ideas on how to fix this??
    Thanks
    -rolo

    Exception says "java.io.IOException: failed to load image contents"
    most probably you are trying to send an image which has had an eror when loading the image.
    See the image load status of the image icon.

  • Sending 2 objects through sockets?

    Hi there,
    I have 2 questoins here...
    The first is....
    Ive made a simple game that moves a image around a screen using the arrow keys. When i start the server it listens for connections and then I run the client. I'm able to get 2 instances of the objects running in 2 different swing frames but at the moment when I move the image around the screen it only moves in one window and not in the other. I would like the coordinates of the image in one window to be the same as the other when I move it.
    this is my server class...
      public void run() {
               try {
                  oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());i move the pacmanGame on my PacmanGamePanel(pgp) which is on a pacmanGameFrame(pgf)
    This is my Client class....
    public static void main(String argv[]) {
                PacmanGameFrame pgf = new PacmanGameFrame();
               ObjectOutputStream oos = null;
               ObjectInputStream ois = null;
               //ObjectInputStream ois2 = null;
               Socket socket = null;
               PacmanGame pacgame = null;
               Ghost ghost = null;
               int port = 4444;
               try {
                 // open a socket connection
                 socket = new Socket("localhost", port);
                 // open I/O streams for objects
                 oos = new ObjectOutputStream(socket.getOutputStream());
                 ois = new ObjectInputStream(socket.getInputStream());
                 //ois2 = new ObjectInputStream(socket.getInputStream());
                 while (true) {
                        // read an object from the server
                        pacgame = (PacmanGame) ois.readObject();
                        ghost = (Ghost) ois.readObject();
                        oos.reset();
                        I was hoping you could tell me why its not sending the object over from my client.
    The second thing is i've coded a Ghost class the exact same way as my PacmanGame class which contains how the image moves around the screen and its methods etc. For some reason its not displaying at all on either the client or the server when i try to send the object across.
    I am trying the same way as sending the pacmanGame() but it doesn't work....
    public void run() {
               try {
                  oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());I have a panel class which prints out the coordinates of the ghost
    public void paint(Graphics g) {
            super.paint(g);
            if(ingame) {
                 Graphics2D g2d = (Graphics2D)g;
                g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
            for (int i = 0; i < ghosts.size(); i++) {
                 Ghost ghost = (Ghost)ghosts.get(i);
                 if(ghost.isVisible())
                      g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
            g2d.setColor(Color.WHITE);
            else {
                 System.out.println("GAME OVER");
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }Help on either question would be great.
    1. why wont the image move on both server and client sides.
    2. How can i get my ghost class to display?
    If you need more info/code let me know..
    Thanks alot.

    Ok i called flush() on the output and commented out reset() on the input but still the same problem.
    oos.writeObject(pgf.getPacmanGamePanel().getPacmanGame());
                  oos.writeObject(pgf.getPacmanGamePanel().getGhost());
                  oos.flush();
    pacgame = (PacmanGame) ois.readObject();
                        ghost = (Ghost) ois.readObject();I think i've figured it out now and its to do with my paint() within gamePanel..
    public class PacmanGamePanel extends JPanel implements ActionListener {
        private Timer timer;
        private PacmanGame pacmanGame;
        private Ghost ghost;
        private ArrayList ghosts;
        private boolean ingame;
        private int B_WIDTH;
        private int B_HEIGHT;
        private int[][] pos = {
                  {50, 50}
    public void paint(Graphics g) {
            super.paint(g);
            if(ingame) {
                 Graphics2D g2d = (Graphics2D)g;
                g2d.drawImage(pacmanGame.getImage(), pacmanGame.getX(), pacmanGame.getY(), this);
            for (int i = 0; i < ghosts.size(); i++) {
                 Ghost ghost = (Ghost)ghosts.get(i);
                 if(ghost.isVisible())
                      g2d.drawImage(ghost.getImage(), ghost.getX(), ghost.getY(), this);
            g2d.setColor(Color.WHITE);
            else {
                 System.out.println("GAME OVER");
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }Can you help?

  • Serialization over sockets

    Hi All!
    So i've decided to perform serialization over sockets - so i made a server that has an ObjectOutputStream and a client that has ObjectInputStream and i wrote a Properties object.
    I managed to get passed the EOFException problem and the same object writing problem (using reset()), but i've read that this isn't efficient, and on top it all it has the problem of blocking.
    I've read some posts regarding Serialization and NIO but i couldn't get from them what i should do - so can someone plz explain to me:
    1) How can i write objects to sockets using NIO
    2) Furthermore - if this really solves the memory and efficiency problems
    3) A code sample or a ref. would really be appriciated.
    Regards,
    Snayit

    Basically I would ask myself if I really need NIO - for MOST purposes the old-blocking IO is very good and much easier to use.
    One of the biggest problems with blocking IO is, that for thousands of clients you need an own thread which causes many OSes to truggle.
    I really recommend buffering the streams! (Via BufferedInput/OutputStream) but do not forget to flush() them if you really want the data to be sent.
    If you want to use NIO you have to write the object-data into a byte-array (creating a bytearrayoutputstream -> ObjectOutputStream) and writing this byte-arrays.
    hope this helps, lg Clemens

  • Problem in passing/returning objects over dynamic web service call

    Hi Friends,
    I am beginner in java web service.
    Here is the problem I am facing when I pass/return user defined objects to remote web service method using dynamic we service call.
    The client can call the remote web service method in 2 ways.
    1. By generating client stubs using WSDL file
    - In this case, I am able to pass/return the user defined objects to remote method without any issue only when the server side web services are deployed in any server(jboss)
    - But in java 1.6 & above, the web services can be deployed without server using endpoint. In this case, I am not able to pass/return objects over web service calls.
    2. Without generating client stubs (dynamic web service call)
    - This will establish a connection at run time using the given WSDL file (I have attached the document). I have to form an XML(This will contain API name, arguments) string as input at run time
    - In this case, it allows only string as argument while passing & returning.
    Please let me know if you can help me on this.
    Regards,
    pani

    I'm not sure about your question, but this might help:
    [http://forum.java.sun.com/thread.jspa?threadID=5251188|http://forum.java.sun.com/thread.jspa?threadID=5251188]
    You might also want to read on JAXB.

  • What is the advantage of using RMI over socket connection

    plz tell me guys what is the advantage of using RMI over socket connection bcoz inherently RMI also uses socket connection.so what is the exact difference in between thm and what is the advantage of using RMI over socket connection.

    i knew tht bt i http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal — in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Filetransfer over sockets

    hi,
    im currently working on a filetransfer over sockets. this is what i do:
    i have a connection from the client to the server. on both sides i have a PrintStream for the output and a bufferedReader to read the responses. the client asks for a file and the server answers with the md5-hash size of the file, so that the client knows how many bytes it has to read. that works fine.
    now the filetransfer:
    the server writes the bytes of the file directly to the OutputStream (not the PrintStream). the client opens a BufferedInputStream on the mentioned socket and reads in as many bytes, as the server said before.
    now the problem:
    sometimes the filetransfer works fine, but sometimes some bytes are missing. i wonder where they are gone. it cant be a problem with the flush() method, because im using OutputStream to send the data. (i tested BufferedOutputStream with flush() with the same results).
    maybe it's not working because a attached a BufferedReader and a BufferedInputStream to the InputStream on the client-side...
    does anybody know, whats going wrong?
    let me know if you want to see some code.
    greetings,
    henrik

    i have solved this problem by using java.nio

Maybe you are looking for