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.

Similar Messages

  • 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 Non-Serializable Objects

    I'm trying to make my server program send a non-serializable object to the client program. But I'm getting a 'java.io.NotSerializableException'. Is there any way to send a non-serializable object through an ObjectOutputStream, or through some other type of stream object?
    Thanks.
    ~jon

    I have some experience before, here is one solutions:Well, nice to know, but its not a solution to the problem discussed in this topic though.
    >
    >
    using toByteArray to get a byte[] and a length of the
    array
    then using the following format to send through
    sockets,
    [bytearray.length][byte array content]
    It really works in a project of a MMS system I have
    worked on.

  • Serialializing non serializable objects

    Hi guys,
    I have to serialize (and then send through socket) a class which implements java.io.Serializable. This class also has some reference with other classes, which should be serialized togheter.
    But when I run the main class (which only serializes) , java.io.NotSerializableException is thrown.
    How do I recognize if a class is effectively serializable?
    How do I serialize too even with non-serializable objects?
    (I need all these objects)
    note : In the class I have only put the marker "implements java.io.Serializable",should I have to do somenthing else?
    Thank You for your great help!

    Hi guys,
    I have to serialize (and then send through socket)a
    class which implements java.io.Serializable. This
    class also has some reference with other classes,
    which should be serialized togheter.
    But when I run the main class (which onlyserializes)
    , java.io.NotSerializableException is thrown.
    How do I recognize if a class is effectively
    serializable?
    How do I serialize too even with non-serializable
    objects?
    (I need all these objects)
    note : In the class I have only put the marker
    "implements java.io.Serializable",should I have todo
    somenthing else?
    Thank You for your great help!I wish there was a utility that could inspect a
    Class, traverse its containment tree and flag
    serializability issues. This could be more powerful
    if generics are used.
    To solve your problem besides the marker, implement
    methods writeObject and readObject and serializing
    the contained object that is not serializable by
    hand. For example if your class is X which contains Y
    that is not serializable then you need to serialize
    fields Y in X.writeObject and construct a Y object in
    X.readObject:
    class Y { // not serializable and you cannot modify
    it
    int i;
    int j;
    Y(int i, int j)
    class X implements Serializable {
    String xyz;
    Y y;
    private void writeObject(ObjectOutputStream out)
    throws IOException{
    out.writeObject(xyz);
    out.writeInt(y.getI());
    out.writeInt(y.getJ());
    private void readObject(ObjectInputStream in)
    throws IOException{
    xyz = (String) in.readObject();
    int i = in.readInt();
    int j = in.readInt();
    y = new Y(i, j);Remember to maintain the same order in readObject and
    writeObject.
    Hi guys,
    I have to serialize (and then send through socket)a
    class which implements java.io.Serializable. This
    class also has some reference with other classes,
    which should be serialized togheter.
    But when I run the main class (which onlyserializes)
    , java.io.NotSerializableException is thrown.
    How do I recognize if a class is effectively
    serializable?
    How do I serialize too even with non-serializable
    objects?
    (I need all these objects)
    note : In the class I have only put the marker
    "implements java.io.Serializable",should I have todo
    somenthing else?
    Thank You for your great help!I wish there was a utility that could inspect a
    Class, traverse its containment tree and flag
    serializability issues. This could be more powerful
    if generics are used.
    To solve your problem besides the marker, implement
    methods writeObject and readObject and serializing
    the contained object that is not serializable by
    hand. For example if your class is X which contains Y
    that is not serializable then you need to serialize
    fields Y in X.writeObject and construct a Y object in
    X.readObject:
    class Y { // not serializable and you cannot modify
    it
    int i;
    int j;
    Y(int i, int j)
    class X implements Serializable {
    String xyz;
    Y y;
    private void writeObject(ObjectOutputStream out)
    throws IOException{
    out.writeObject(xyz);
    out.writeInt(y.getI());
    out.writeInt(y.getJ());
    private void readObject(ObjectInputStream in)
    throws IOException{
    xyz = (String) in.readObject();
    int i = in.readInt();
    int j = in.readInt();
    y = new Y(i, j);Remember to maintain the same order in readObject and
    writeObject.

  • Non Serializable Objects

    I am working on a java project and I have to serialize a class (created by me) which has many references to other classes that should be serialized too.
    I add the marker "implements serializable" to all the necessary classes, but when I run I get a non serializable exception.
    Maybe one ore more objects are non serializable, but how do I identify them?
    I've read that If I have to serialize non serializable objects, I need to write my own writeObject(ObjectOutputStream out)throws IOException and readObject(ObjectInputStream in) , but I don't know how to implement and us them.
    note : I can't use transient beacuse I need everything to be serialized!
    Thanks a lot. Bye!

    Now I'll post my code, If anyone knows how to serialize (and then deseserialize) the class "AgentMessage" , and its subclasses "StaticPart" and "DynElement" from the main class , I'll be grateful.. It's about 2 days I'm working on it and I continue getting "nonserialializable exception" ...
    thank you guys
    package agentsLibrary;
    //some imports
    public class AgentMessage implements Serializable{
         private static final long serialVersionUID = 1L;
         private StaticPart sp;
         private DynElement de;
         public AgentMessage(String agent,byte[] code,String mainclass,Certificate signerId,PrivateKey priv,String configuration,Serializable dclear,byte[] dsecret,PathEl[] dpath,byte[] c){ //costruttore
              sp=new StaticPart(agent,code,mainclass,signerId,priv,configuration);
              de=new DynElement(dclear,dsecret,c,dpath);
         public StaticPart getSp(){
              return sp;
         public DynElement getDe(){
              return de;
         private void writeObject(java.io.ObjectOutputStream out) throws IOException{
              System.out.println("class implements writeObject( )");
              //depends on the method to store out all the important state
              //out.defaultWriteObject();//perform the default serialization(va sempre fatto il default)
              out.writeObject(sp);
              out.writeObject(de);
         private void readObject(java.io.ObjectInputStream in)throws ClassNotFoundException, IOException {
              System.out.println("class implements readObject( )");
              //in.defaultReadObject();
              sp=(StaticPart)in.readObject();
              de=(DynElement)in.readObject();
    package agentsLibrary;
    public class StaticPart implements Serializable{
         private static final long serialVersionUID = 1L;
         private String agent="";
         private byte[] code=null;
         private String mainclass="";
         private Certificate signerid=null;
         private PrivateKey priv=null;
         private Calendar timestamp=null;
         private Signature sig=null;
         private byte[] buffertotale=null;
         private byte[] firma=null;
         private String configuration="";
         public StaticPart(String agent, byte[] code, String mainclass, Certificate signerid, PrivateKey priv,String configuration){
              this.configuration=configuration;
              this.code=code;
              this.mainclass=mainclass;
              this.agent=agent;
              this.priv=priv;
              this.signerid=signerid;
              timestamp=Calendar.getInstance();
              Date time=new Date();
              time=timestamp.getTime();//Gets this Calendar's current time.
              try {
                   byte[] nomeagent=agent.getBytes("8859_1");//converto stringa
                   byte[] mainclas=mainclass.getBytes("8859_1");//converto stringa
                   byte[] signer=signerid.getEncoded();
                   byte[] priva=priv.getEncoded();
                   byte[] dat=null;
                   dat=time.toString().getBytes("8859_1");
                   buffertotale=new byte[nomeagent.length+mainclas.length+signer.length+priva.length+dat.length+code.length];
                   System.arraycopy(nomeagent, 0, buffertotale, 0, nomeagent.length);
                   System.arraycopy(code, 0, buffertotale, nomeagent.length, code.length);
                   System.arraycopy(mainclas, 0, buffertotale, code.length, mainclas.length);
                   System.arraycopy(signer, 0, buffertotale, mainclas.length, signer.length);
                   System.arraycopy(priva, 0, buffertotale, signer.length, priva.length);
                   System.arraycopy(dat, 0, buffertotale, priva.length, dat.length);
              } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
                   System.exit(1);
              } catch (CertificateEncodingException e) {
                   e.printStackTrace();
                   System.exit(1);
              try {
                   sig = Signature.getInstance(priv.getAlgorithm());
                   sig.initSign(priv);
                   sig.update(buffertotale, 0, buffertotale.length);
                   firma=sig.sign();
              } catch (SignatureException e) {
                   e.printStackTrace();
                   System.exit(1);
              } catch (InvalidKeyException e) {
                   e.printStackTrace();
                   System.exit(1);
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
                   System.exit(1);
         public boolean verify() {
              try{
                   PublicKey pub=signerid.getPublicKey();
                   Signature sig = Signature.getInstance(pub.getAlgorithm());
                   sig.initVerify(pub);
                   sig.update(buffertotale, 0, buffertotale.length);
                   return sig.verify(firma);
              } catch (SignatureException e) {
                   e.printStackTrace();
                   System.exit(1);
              } catch (InvalidKeyException e) {
                   e.printStackTrace();
                   System.exit(1);
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
                   System.exit(1);
              return false;
         public String getAgentName() {
              return agent;
         public byte[] getCode() {
              return code;
         public String getClassName() {
              return mainclass;
         public PrivateKey getPrivate() {
              return priv;
         public Certificate getId() {
              return signerid;
         public byte[] getSignature(){
              return firma;
         public String getConfiguration(){
              return configuration;
    package agentsLibrary;
    import java.io.Serializable;
    public class DynElement implements java.io.Serializable{
         private static final long serialVersionUID = 1L;
         private Serializable dclear=null;
         private byte[] dsecret=null;
         private PathEl[] dpath=null;
         private byte[]c=null;
         public DynElement(Serializable dclear,byte[] dsecret,byte[]c,PathEl[] dpath){
              this.dclear=dclear;
              this.dsecret=dsecret;
              this.c=c;
              this.dpath=dpath;
         public byte[] getC() {
              return c;
         public Serializable getDclear() {
              return dclear;
         public PathEl[] getDpath() {
              return dpath;
         public byte[] getDsecret() {
              return dsecret;
    //finally the following is the main class that should serialize
    AgentMessage msg=new AgentMessage(name,code,mainclass,signerId,privata,configuration,dclear,dsecret,dpath,c);
              try {
                   System.out.println("Sending Agent Message to Server "+ip+":"+port);
                   Socket s = new Socket(ip,port);
                   ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
                   out.writeObject(msg);
                   out.flush();
                   s.close();
              } catch (Exception e) {
                   return false;
              return true;
         }

  • Returning Non Serializable Objects

    Is it possible in anyway to return non serializable objects from the remote method of an EJB, for instance return a result set. Everytime i try, i get a CORBA marshalling exception, i tried to put the resultset in a serilized object such as an enumeration or vector but got the same error when retreiving it from the enumeration or vector. Help is needed and appreciated. Thanx.

    Is it possible in anyway to return non serializable objects from the remote method of an EJB, for instance return a result set. Everytime i try, i get a CORBA marshalling exception, i tried to put the resultset in a serilized object such as an enumeration or vector but got the same error when retreiving it from the enumeration or vector. Help is needed and appreciated. Thanx.

  • Inserting non-serializable objects

    Is there any way to insert non-serializable objects into a database? (Or to convert them to bytes?)

    Is there any way to insert non-serializable objectsinto a database?
    A joke right?No, it's not a joke. It would be a pretty bad one if it were.
    Yes, there is a way. Create a table that corresponds
    to the object where each attribute in the object
    corresponds to field in the object. Add a unique key
    if one doesn't exist.I wish it were that simple. I don't have access to those attributes...
    >
    To create an object insert a row into the table. To
    load the object use the unique key to query for the
    row. To 'delete' the object delete the row from the
    table.BTW, the object in question is the java.awt.geom.Area object (http://java.sun.com/j2se/1.3/docs/api/java/awt/geom/Area.html ).
    The only way I can think of to insert an object that doesn't map to a SQL type is to convert it to bytes through serialization, and insert it as RAW data.
    I've extended Area to add a name and made my class serializable. However, since Area is not serializable, the only data I can retrieve after deserializing is the name I added (from my understanding of serialization, I have to save Area's data myself, but can't since I don't have access to it, so the deserialization process calls the Area() constructor which initializes the object to empty).

  • Non-Serializable objects in webservice

    Hi everyone,
    I'm writing a webservice that connects and performs update on a third-party
    data repository (document management system) through the vendor provided
    framework.
    Some of the objects used in the framework are not serialized, and WebLogic
    Workshop 7.0 won't compile my services because they contain non-serializable
    objects. Those objects are not used as messages or method parameters, rather
    are the member variables of the services.
    My question is how would I go about using non-serialized objects in a
    webservice class with WebLogic Workshop 7.0? I've seen some Apache AXIS
    webservice examples that does the similar thing, but some of the services
    works with non-serializable objects. Do I need to create an EJBcontrol that
    masks non-serializable objects to be used with the webservice?
    Any input is greatly appreciated. I'm still new at webservice programming.
    Thank you,
    Makoto

    Hi everyone,
    I'm writing a webservice that connects and performs update on a third-party
    data repository (document management system) through the vendor provided
    framework.
    Some of the objects used in the framework are not serialized, and WebLogic
    Workshop 7.0 won't compile my services because they contain non-serializable
    objects. Those objects are not used as messages or method parameters, rather
    are the member variables of the services.
    My question is how would I go about using non-serialized objects in a
    webservice class with WebLogic Workshop 7.0? I've seen some Apache AXIS
    webservice examples that does the similar thing, but some of the services
    works with non-serializable objects. Do I need to create an EJBcontrol that
    masks non-serializable objects to be used with the webservice?
    Any input is greatly appreciated. I'm still new at webservice programming.
    Thank you,
    Makoto

  • Failed to replicate non-serializable object  Weblogic 10 3 Cluster environ

    Hi,
    We have problem in cluster environment, its showing all the objects in Session needs to be serialized, is there any tool to find what objects in session needs to be serialized or any way to find. There was no issue in WLS 8 when the application again setup in WLS 10, we are facing the session replication problem.
    The setup is there are two managed server instance in cluster, they are set to mulicast(and also tried with unicast).
    stacktrace:
    ####<Jun 30, 2010 7:11:16 PM EDT> <Error> <Cluster> <userbser01> <rs002> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1277939476284> <BEA-000126> <All session objects should be serializable to replicate. Check the objects in your session. Failed to replicate non-serializable object.>
    ####<Jun 30, 2010 7:11:19 PM EDT> <Error> <Cluster> <userbser01> <rs002> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1277939479750> <BEA-000126> <All session objects should be serializable to replicate. Check the objects in your session. Failed to replicate non-serializable object.>
    Thanks,

    Hi
    Irrespective of WLS 8.x or WLS 9.x, 10.x, in general any objects that needs to be synced/replicated across the servers in cluster should be Serializable (or implement serializable). The object should be able to marshall and unmarshall. Simple reason why it did not showed in WLS 8.x is may be in that version they could not show these details like Error. May be they showed as Info or Warn or Just Ignored it. Weblogic Server became more and more stable and more efficient down the lines like from its oldest version 4.x, 5.x, 6.x, 7.x to latest 10.x. So my guess is they added more logic and more functionality to capture all possible errors and scenarios. I did worked on WLS 8.1 SP4 to SP6 long time back. Could not remember if I saw or did not see these errors for cluster domain with non-serializabe objects. I vaguley remember seeing it for Portal Domains but not sure. I do not have 8.x installed, otherwise I would have given a quick shot and confirm it.
    So even though it did not showed up in WLS 8.x, still underneath rule is any object that needs to be replicated that is getting replicated in cluster needs to implement Serializable interface.
    Thanks
    Ravi Jegga

  • HOW TO PASS NON REMOTE OBJECT PARAMETER

    good day,
    hi im new to java and rmi, and i need help pls, my question is how can i pass a non-remote object/local object as a parameter to a remote method. can u pls give a code for the:
    1. client that will invoke the remote method and pass the object in remote objects method.
    2. object that will be passed to the server/remote object( a serilizable object of course).
    3. the remote object and the method that will receive the object parameter.
    thank you very much for your kindness,
    p.s.
    you can email me to [email protected]
    batusai,

    When you create the object locally, and pass it to the server, at that point it exists on both systems/in both jvms.
    Why don't you write your own example, and try it. If you get in trouble, post the code, and we will help you.

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

  • 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();
    }  

  • Java 5, Linux, 64-bit: Non-ASCII chars over socket

    Hi,
    I am having issues with reading non-ASCII chars from a socket. I send a mixed message, with the first part in ASCII and the last bit in non-ASCII. There are no issues with reading the non-ASCII characters on Windows. However, when I try running the server on Linux. The following is a message sample:
    Start message<CRLF>
    &#1092;&#1074;&#1072;&#1092;&#1099;&#1074;&#1072;&#1092;&#1074;&#1099;&#1072;&#1092;&#1099;&#1074;<CRLF>
    The second part (which is encoded in either Windows-1250 or KOI8-R), comes out as 3F (when you look at the bytes) on Linux.
    Any suggestions?
    Thanks,
    Max

    You must be using Readers and Writers, and you need to make sure you specify the same charsets when constructing them. Don't leave this to the default, as this seems to vary across platforms and definitely has varied across releases.

  • Store non-serializable object in session

    Dears,
    I am storing an object in the session but after some requests the object gets null. A friend told me that happens because that object is not serializable.
    Is that true? and how to fix this?
    Thanks in advance
    BISO

    biso wrote:
    I am storing an object in the session but after some requests the object gets null. A friend told me that happens because that object is not serializable.
    Is that true? Only if the application server is configured to persist the sessions on shutdown and it is been restarted while you was using/testing the webapp. But you should have seen a NotSerializableException in the application server logs, which is fairly self-explaining.
    and how to fix this?Implement [java.io.Serializable|http://java.sun.com/javase/6/docs/api/java/io/Serializable.html].
    Or just don't restart the appserver while you're testing on the same session.

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

Maybe you are looking for