Java network object serialization

Hello all,

Im trying to send an object from client to server and one of the object states is a vector and the other is a string. I can access the string on the Server side, but the vector contents is zero on the server side..Can someone help me out please..
// Server
import java.net.*;   
import java.util.Vector;
import java.io.*;
public class SimpleServer {
	
	public static void main(String args[]) {
		int port = 2002;
		try {
			System.out.println("Hello");
			ServerSocket ss = new ServerSocket(port);
			Socket s = ss.accept();
			System.out.println("Hello 2");
			InputStream is = s.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			testobject to = (testobject)ois.readObject();
			System.out.println("Vector size : " + to.vectorX.size() + " and object.id : "
					+ to.id);
/*			if (to != null) {
				for(int i = 0; i < to.vectorX.size(); ++i )
				System.out.println("Output 1 : " + to.vectorX.elementAt(i));
			}   */
			is.close();
			s.close();
			ss.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


// Client
import java.net.*;
import java.io.* ;
import java.util.Vector;

public class SimpleClient {
	
    protected static Vector<String> vectorX = new Vector<String>();
    
    public SimpleClient(){
    	vectorX.addElement("hello");
    	vectorX.add("goodbye");
    	vectorX.add("finally");   
    }
	
	public static void main(String args[]) {
		try {
			new SimpleClient();
			Socket s = new Socket("localhost", 2002);
			OutputStream os = s.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			testobject to = new testobject(1, "theID", vectorX );
			System.out.println(vectorX.size());
			oos.writeObject(to);
//			oos.writeObject(new String("another object from the client"));
			oos.close();
			os.close();
			s.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}


//testobject
import java.net.*;
import java.io. * ;
import java.util.Vector;
class testobject implements Serializable {
	int value;
	String id;
	Vector<String> vectorX; 
	
	public testobject(int v, String s, Vector<String> vector) {
		this.value = v;
		this.id = s;
		this.vectorX = new Vector<String>();
	}
}

Open in new window

oggiemcAsked:
Who is Participating?
 
falterCommented:
Hi,

replace the line  in testobject constructor
this.vectorX = new Vector<String>();

with

this.vectorX = vector;

and it will work.

The first statement will always transfer an empty vector to the server.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.