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

Similar Messages

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

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

  • Problem with Sending files over Sockets

    Hi. I have a problem when I try to send files over sockets. When I send text files it works well but when I try to send .jpg or other kind of files it doesn't work well because some characters are wrong, I hope you can help me.
    Here is my code:
    //Sender code
    import java.io.*;
    import java.net.*;
    class Servidor{
         Servidor(){
              try{
                   String arch="art.jpg";
                   ServerSocket serv=new ServerSocket(125);
                   Socket socket=serv.accept();
                   System.out.println("Conectado");
                   int c;
                   BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   FileInputStream fis=new FileInputStream(arch);
                   File f=new File(arch);
                   bw.write(""+f.length());
                   bw.newLine();
                   bw.flush();
                   System.out.println("Escribiendo");
                   while((c=fis.read())!=-1){
                        bw.write(c);
                   bw.flush();
                   fis.close();
                   System.out.println("Terminado");
                   while(true){
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Servidor();
    //Client code
    import java.io.*;
    import java.net.*;
    class Cliente{
         Cliente(){
              try{
                   Socket socket=new Socket("localhost",125);
                   System.out.println("Conectado");
                   BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   long tam=Long.parseLong(br.readLine());
                   long act=0;
                   FileOutputStream fos=new FileOutputStream("resp.jpg");
                   System.out.println("Recibiendo: "+tam);
                   while(act<tam){
                        fos.write(br.read());
                        act++;
                   System.out.println("Terminado: "+act+" / "+tam);
                   fos.close();
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Cliente();
    }

    I don't think you want BufferedReader and OutputStreamWriter, you want ByteArrayOutputStream and ByteArrayInputStream . The problem is that you are sending jpegs (binary data) as text.

  • My appstore wont let me download anything. It says i have to agree to the terms and i agree and again it pop up the same thing over and over! Please help me

    My appstore wont let me download anything. It says i have to agree to the terms and i agree and again it pop up the same thing over and over! Please help me

    I thought i was the only one!! but its happening on my ipad! and i dont even want to try on my iphone uhhh its annoying!

  • Please help me, mail wont send!!! Please help me!!!!

    Please help me, mail wont send!!! Please help me!!!!
    I have not changed anything but today cant send mail!
    Any help would be most appreciated.

    Try deleting and recreating the account on the iPad.

  • PASSWORD FOR FLODERS  PLEAse  HELP URGENT

    HI ALL
    please tell me the method of implementing password
    provision for some folders/files in the system.
    it should ask for password authentification before
    opening when i click on the folder.
    please help urgent
    thanks
    belur

    Hi Swaroopba,
    It can be very well done thru Form based Authentication.
    For eg let me explain with respect to Tomcat.
    Go to
    $TOMCAT_HOME/webapps/examples/WEB-INF directory.
    Please add the following code in it.
    <security-constraint>
    <web-resource-collection>
    <web-resource-name>Protected Area </web-resource-name>
    <!-- Define the context URL's to be protected -->
    <url-pattern>/jsp/security/protected</url-pattern>
    </web-resource-collection>
    </security-constraint>
    Please add the following code in it. And you have to specify the roles for it.
    I hope this will be helpful for you.
    Or if you want it in an application, please let me know.
    Thanks
    Bakrudeen

  • I want to buy an in-app purchase but i don`t remember my security questions and i cant access my recovery email either, what can i do? i have 100$ on my account and cant use it because of that problem, please help URGENT

    I want to buy an in-app purchase but i don`t remember my security questions and i cant access my recovery email either, what can i do? i have 100$ on my account and cant use it because of that problem, please help URGENT

    If you have a rescue email address on your account then you can use that - follow steps 1 to 5 half-way down this page will give you a reset link on your account : http://support.apple.com/kb/HT5312
    If you don't have a rescue email address (you won't be able to add one until you can answer your questions) then you will need to contact Support in your country to get the questions reset : http://support.apple.com/kb/HT5699

  • Please help URGENT : Chinese handwriting doesn't seem to work on Lion OSX. the handwriting trackpad appears but anything i write in Chinese doesn't appear in word, chrome,..... HELP PLEASE

    please help URGENT : Chinese handwriting doesn't seem to work on Lion OSX. the handwriting trackpad appears but anything i write in Chinese doesn't appear in word, chrome,..... HELP PLEASE
    And in system prefs/language and text/input languages, simplified chinese and traditional chinese are ticked as usual with handwriting options on !!!!

    Please search the forum for "chinese" to find the many other earlier posts about your issue, like
    https://discussions.apple.com/message/15746805#15746805

  • I bought an iphone 5 on 01 February 2013 from your store to use in Turkey. But the phone is sim-locked. What can I do now?  Please help urgently.

    I bought an iphone 5 from apple store in Geneva to use in Turkey. But it is sim-locked. What can I do now. Please help urgently.

    Return it to the store where you purchased & get your money back. Either that, or call the store. No one here can help you, as there is no one from Apple here.

  • Please Help - Urgent

    Hi everyone, I�m having problems with Java Mail, I have just installed it along with the java activation framework, they are located in the following directories:
    JavaMail: C:\jdk1.3.1\lib\javamail-1_2[1]
    Java activation framework: C:\jdk1.3.1\lib\jaf1_0_1[1]
    I have the classpath set as: C:\jdk1.3.1\lib\mail.jar;C:\jdk1.3.1\lib\activation.jar
    When I try to compile the sample code provided with these packages, msgsend.java using Jbuilder 2 I get the following errors:
    Error (36): cannot access directory javax\mail.
    Error (37): cannot access directory javax\mail\internet.
    Error (209): class message not found in class msgsend.
    Error (210): class MessagingException not found in class msgsend
    Error (134): class Session not found in class msgsend
    Error (134): variable Session not found in class msgsend
    Error (139): class Message not found in class msgsend
    Error (139): class MimeMessage not found in class msgsend
    Error (141): class InternetAddress not found in class msgsend
    Error (145): cannot access class Message.RecipientType;neither class nor source found for Message.RecipientType.
    Error (146): Variable InternetAddress not found in class msgsend
    Error (148): cannot access class Message.RecipientType;neither class nor source found for Message.RecipientType.
    Error (149): Variable InternetAddress not found in class msgsend
    Error (151): cannot access class Message.RecipientType;neither class nor source found for Message.RecipientType.
    Error (152): Variable InternetAddress not found in class msgsend
    Error (162): Variable Transport not found in class msgsend
    Error (170): class Store not found in class msgsend
    Error (172): class URLName not found in class msgsend
    Error (172): class URLName not found in class msgsend
    Error (189): class Folder not found in class msgsend
    Error (195): Variable Folder not found in class msgsend
    Error (197): class Message not found in class msgsend
    Error (197): class Message not found in class msgsend
    If I try to use another Java package to compile it I get even more errors (52), I cannot compile it by using the Javac command line compiler, it just says �Bad command or file name�.
    Can anyone tell me Why this is happening and how I might be able to fix it please, I need to start learning Java Mail quickly but at the moment I can�t even begin to do this until I can understand how to get this sample code to work.
    Thanks Everyone
    Noel

    First of all... don't post with topics like "Please Help - Urgent". The topic is supposed to reflect what the question is about.
    Secondly... think for a second. If mail.jar is in C:\jdk1.3.1\lib\javamail-1_2[1]... why are you with your classpath saying that mail.jar is in C:\jdk1.3.1\lib ?
    You classpath is supposed to point directly at you jar-files.
    /Michael

  • How to download garageband old version? i mean version 1.0 to install it on iphone 4s with ios 6.0.1??? please help urgently, how to download garageband old version? i mean version 1.0 to install it on iphone 4s with ios 6.0.1??? please help urgently

    how to download garageband old version? i mean version 1.0 to install it on iphone 4s with ios 6.0.1??? please help urgently, how to download garageband old version? i mean version 1.0 to install it on iphone 4s with ios 6.0.1??? please help urgently

    I did this a few weeks ago to be sure it was going to work for a young person I was giving my ipod to.  Then I reset the information for her and now it will not load.  Very sad.  She is so talented and she really needs this.   Anyone know?

  • I received an iCloud backup notification on my ipad mini but tapping "OK" does not remove it and therefore I am unable to do any activity on my ipad mini. please help urgent.

    I received an iCloud backup notification on my ipad mini but tapping "OK" does not remove it and therefore I am unable to do any activity on my ipad mini. please help urgent.??

    Have you tried a reset ? Press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider if it appears), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot.

  • Tried to download TV series from ITunes.  .  All I get is:  download error.  Tap to retry.   Repeats over and over.  Please help!

    Tried to download TV series from ITunes.  Most ok, but 4 will not download.  All I get is:  download error.  Tap to retry.   Repeats over and over.  Please help!

    If you sync with iTunes on your computer - connect the iPad to your computer and launch iTunes. Click on the iPad name on the left side. Then at the top of iTunes go to Store>Check for available downloads. See if the TV shows will download there and then sync them to the iPad.
    If you don't sync with iTunes, try signing out of your account, restart the iPad, sign in again and then try to download the shows again.
    Settings>Store>Apple ID. Tap your ID and sign out. Restart the iPad by holding down on the sleep button until the red slider appears and then slide to shut off. To power up hold the sleep button until the Apple logo appears and let go of the button.
    Go back to Settings>Store>Sign in and then try to download again.

  • TS2755 the pic butten on messages is not working. can not send or recieve photos. please help.

    the pic butten on messages is not working. can not send or recieve photos. please help.

    Hi Beharley,
    try resetting your network settings: Settings - General - Reset - Reset Network Settings. This works fine if something is messed up with your carrier bundle.
    Regards, Peter

Maybe you are looking for

  • 990XA-GD55-One Click Bios 2 In Windows Download? 2133 DDR3 Ram?

    I am new to this site.I have been using these boards for awhile now..I noticed that most of my builds, that have one click bios 2...will have a download for one click bios 2, that you can use on your desktop..I like this feature and i have used it on

  • Array Index out of bound exception

    public Name[] getName() {           Name[] retVal = new Name[0];           retVal[0] = this.getNameInstance();           return retVal;      public void setName(Name[] theName) {           theName[0]=this.getNameInstance();      private Name myNameIn

  • Mini window/adjustment display

    I am using Lightroom 2.0 beta. Whenever I make any adjustment (sharpen etc) a small mini adjustment window is displayed over the photo. Can anyone please tell me how to make this window go away - it stays there no matter what I do (even shows through

  • Total sales values by material and plant

    Hi, I was trying to extract the following information: material number, plant, total sales qty(2006), and total sales amount(2006) from sap table. So, can any one help me with the table or a report where in I can find all this information. Thanks Put

  • Change value in service entry sheet

    Hello, Can we change the values In Service entry sheet.if yes how and no why? Regards sap man