Java tcp object serialization

Hello all,

Im having a bit of difficulty retrieving object states on the server side. I want to send MusicStream objeccts from client to server (please see attached code). The probem is, on the server side my username is coming up as null and the musicVector keeps printing the first element even though i ask for lastElement(). The text state is printing out the right value : "text". Can someone see what im doing wrong? Ive attached a trimmed version of my client and server code to make it easier to read, if more code is required please ask. Thanks
// MusicStream Class Server

import java.io.Serializable;
import java.util.Vector;

public class MusicStream implements Serializable{
	
	protected Vector<String> musicVector;
	private String username;
	private String text = null;
	
	public MusicStream(String username){
		this.username = username;
		this.musicVector = new Vector<String>();
		
	}
	
	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getText() {
		return text;
	}

}

// MusicStream class Client
import java.io.Serializable;
import java.util.Vector;

public class MusicStream implements Serializable{
	
	protected Vector<String> musicVector;
	private String username;
	private String text = "text";

	public MusicStream(String username){
		this.username = username;
		this.musicVector = new Vector<String>();
		
	}
	
	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getText() {
		return text;
	}

}

// Client Code


public void actionPerformed(ActionEvent e) {
	
	if (e.getSource() == loginButton) {
		musicStrm = new MusicStream(username);
		System.out.println("hello there " + musicStrm.getText());
		return choice;
	}
	
	if (isLoggedOn() == false) {
		
		if (loginField.getText().equals("")) {
			appendMessage("Please enter username \n");
		} else {
			LoginBean lb = new LoginBean();
			lb.setUsername(loginField.getText());
			setUsername(lb.getUsername());
			System.out.println("Username : " + getUsername());
			ct = new ClientTransmit(localhost, this);
			t1.start();
			System.out.println("Connected??" + connected);
		}
	} else {
		appendMessage("Already logged on \n");
	}
}

if (e.getSource() == sendButton) {
	
	if (ct.connected == true && (!streamSelect.isSelectionEmpty())) {
		
		if (streamChoice.equals("music")) {
			musicStrm.musicVector.add(message);
			ct.messageTransmit(musicStrm);
		}
	}
}

public void messageTransmit(Object o) {
	Object obj = o;
	String choice = null;
	
	if (obj instanceof MusicStream) {
		MusicStream ms = (MusicStream)obj;
		try {
			System.out.println("About to transmit MusicStream object");
			os.writeObject(ms);
			os.flush();
			this.getServerReply();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

// Server Class
 private boolean readCommand() 
    {
       Object obj = null;

        try 
        {
            obj = is.readObject();

			if(obj instanceof MusicStream){
            	MusicStream ms = (MusicStream) obj;
            	streamService.addMusicMessage(ms);
            	System.out.println("ms.text : " + ms.getText());   // text
            	System.out.println("Username: " + ms.getUsername());  // null
            	System.out.println("In handle connection, first and last element of received " +
            			"vector are " + ms.musicVector.firstElement() + " and " + ms.musicVector.lastElement()); // prints out 1st element each time
            }           
        } 
        catch (Exception e) 
        {
        	System.out.println("In readCommand() exception");
            obj = null;
         //   e.printStackTrace();
            
       }

Open in new window

oggiemcAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:
where is your main() method on the client side?
How would we know what is the order of how you execute it
Also strange taht you have

return choice;

from the void method - should not compiler complain?
0
oggiemcAuthor Commented:
Hi for_yan..Like i said i have trimmed the code down in the hope that the error may be spotted easily..I can post the whole client and server code if needed. Please see attached..
******************** ClientGUI *******************
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ClientGUI extends JFrame implements ActionListener, Runnable {
	public static final int defaultWidth = 80, defaultHeight = 40;
	
	   protected static Thread t1;
	   protected boolean t1Flag = true;
	   
	   protected int count = 0;
	   private boolean loggedOn = false;
	   private String username;	
	   private String localhost = "127.0.0.1";
	   boolean connected = false;
	   
	   private JLabel loginLabel;
	   private JTextField loginField;
	   	
	   private String streamChoice;
	   private ClientTransmit ct;
	   
	   protected FootballStream footyStrm;
	   protected MusicStream musicStrm;
	   
	   private String [] listChoices = {"Football", "Music", "Priestalk", "Film"};
	   
	   private JList streamSelect;
	   private JScrollPane streamScroll;
	   
	   
	   private Button  loginButton;
	   private Button  logoutButton;
	   private Button  sendButton;
	   
	   private JTextArea messageInput;
	   private JScrollPane messageScroll;
	   
	   JTextArea streamDisplay;
	   private JScrollPane streamPane;
	   
	   private JLabel middleLabel;
	   private JLabel bottomLabel;
	   
	   public ClientGUI() {
	        super("ClientGUI");
		    JPanel topPanel = new JPanel();
		    JPanel middlePanel = new JPanel();
		    JPanel bottomPanel = new JPanel();	        	       
	        
	        streamSelect = new JList(listChoices);
	        streamSelect.addListSelectionListener(
        			new ListSelectionListener(){
						public void valueChanged(ListSelectionEvent e) {							
							if (! e.getValueIsAdjusting()){
								streamChoice = getStreamChoice();
	                            }
							}   	
        });
	        
	        messageInput = new JTextArea(7, 20);
	        messageInput.setLineWrap(true);	        
	        messageScroll = new JScrollPane(messageInput, 
	        		ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	        		ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	        
	        streamDisplay = new JTextArea(7, 20);
	        streamDisplay.setLineWrap(true);	        
	        streamPane = new JScrollPane(streamDisplay, 
	        		ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	        		ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	        
	        streamScroll = new JScrollPane(streamSelect, 
	        		ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	        		ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	        
	        loginLabel = new JLabel("Username: ");
	        loginField = new JTextField(6);
	        
	        loginButton = new Button("Login");
	        loginButton.setBackground(Color.white);
	        loginButton.addActionListener(this);
	        
	        logoutButton = new Button("Logout");
	        logoutButton.setBackground(Color.white);
	        logoutButton.addActionListener(this);
	        
	        sendButton = new Button("Send");
	        sendButton.addActionListener(this);
	        
	        middleLabel = new JLabel("Enter text: ");
	        bottomLabel = new JLabel("Display: ");
	        
	        topPanel.add(streamScroll);
	        topPanel.add(loginLabel);
	        topPanel.add(loginField);
	//        topPanel.add(sendButton);	        
	        topPanel.add(loginButton);
	        topPanel.add(logoutButton);
	        middlePanel.add(messageScroll);
	        middlePanel.add(middleLabel, 0);
	        middlePanel.add(sendButton);
	        bottomPanel.add(streamPane);
	        bottomPanel.add(bottomLabel, 0);

	        this.add(topPanel, BorderLayout.NORTH);
	        this.add(middlePanel, BorderLayout.CENTER);
	        this.add(bottomPanel, BorderLayout.SOUTH);

	        this.setSize(450, 450);
	        this.setVisible(true);
	        
	        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	   }
	   
	   
 public static void main(String[] args) {
     t1 = new Thread(new ClientGUI());
}

 
@Override
 public void actionPerformed(ActionEvent e) {
	
	String message = messageInput.getText();
	
	if(e.getSource() == loginButton ){
		
	 if(isLoggedOn() == false){
		
	   if(loginField.getText().equals("")){
		   appendMessage("Please enter username \n");
	  }		
	   else{
//		   System.out.println("Username : " + loginField.getText());
		   LoginBean lb = new LoginBean();
		   lb.setUsername(loginField.getText());
		   setUsername(lb.getUsername());
			
	       System.out.println("Username : " + getUsername());
		   ct = new ClientTransmit(localhost, this);
	//	   connected = true;
		   t1.start();
		   System.out.println("Connected??" + connected);
	//	System.out.println("Please enter username \n");
	   }
	 }
	 else{
		 appendMessage("Already logged on \n");
	 }
	}
	
/*	  if(connected == true){
		System.out.println("Connected?? " + connected);
	  }  */
		
	if(e.getSource()== sendButton){
		
		if(ct.connected == true && (!streamSelect.isSelectionEmpty())){
		System.out.println("Connected?? " + connected);		
		
		if(streamChoice.equals("football")){
	//		footyStrm = new FootballStream(username);
			footyStrm.footyVector.add(message);
			ct.messageTransmit(footyStrm);
		}
		
		else if(streamChoice.equals("music")){
			System.out.println("In music button");
  //			musicStrm = new MusicStream(username);
			musicStrm.musicVector.add(message);
			System.out.println("Message : " + musicStrm.musicVector.firstElement());
			ct.messageTransmit(musicStrm);
			System.out.println("Music vector size " + musicStrm.musicVector.size());
		}
	}
		else {appendMessage("Please login first and make " +
				"sure you have selected a stream choice \n");}			
	}
	
	if(e.getSource() == logoutButton){
		
		ct.messageTransmit("logout");		
	}
 }

 public String getStreamChoice(){
	 
	 String choice = null;
	
	if(streamSelect.getSelectedValue().equals("Football")){
		choice = "football";
		footyStrm = new FootballStream(username);
		System.out.println("Football");
		return choice;
	}
	else{
		System.out.println("Music");
		choice = "music";
		musicStrm = new MusicStream(username);
		System.out.println("hello there " + musicStrm.getText());
		return choice;
	}	
 }
 
 void appendMessage(String ms){
	  
	//  String message = ms.musicVector.firstElement();
	  streamDisplay.append(ms);
  }

 public void setUsername(String username) {
	this.username = username;
 }

 public String getUsername() {
	return username;
 }


public void setLoggedOn(boolean loggedOn) {
	this.loggedOn = loggedOn;
}


public boolean isLoggedOn() {
	return loggedOn;
}


@Override
public void run() {
	
 while(t1Flag)
	try {		
	 t1.sleep(10000);		
	 if(streamChoice.equals("music")){
//		System.out.println("Music 123");
	 }
	 else if(streamChoice.equals("football")){
//		System.out.println("Football 123"); 		 
	 }
	 
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	
}  

}

********************** ClientTransmit *********************
 
import java.net.*;
import java.io.*;
import java.util.*;

public class ClientTransmit{
	
	private String localHost = "127.0.0.1" ;
	private Socket socket = null;
    private ObjectOutputStream os = null;
    private ObjectInputStream is = null;
    private ClientGUI gui;
    boolean connected = false;
    
    public ClientTransmit(ClientGUI cg){   	
    	this.gui = cg;   	
    }

 
    public ClientTransmit(String serverIP, ClientGUI gui) 
    	{
    	this.gui = gui;
    	System.out.println(serverIP);
          if (!connectToServer(serverIP)){ 
        	 System.out.println("Cannot open socket connection...");            
          }
    }

    private boolean connectToServer(String serverIP){ 
    	
	try { // open a new socket to port: 5050 and create streams
	
	   this.socket = new Socket(serverIP,5050);
	   this.os = new ObjectOutputStream(this.socket.getOutputStream());
	   this.is = new ObjectInputStream(this.socket.getInputStream());
	   this.gui.streamDisplay.append("Welcome to fergals chat server " + this.gui.getUsername() + " !");
	   System.out.print("Connected to Server\n");
	   connected = true;
	   this.gui.setLoggedOn(true);
	   return true;
	} 
    catch (Exception ex){ 
	  System.out.print("Failed to Connect to Server\n" + ex.toString());
	  this.gui.appendMessage("Failed to Connect to Server\n");
	  System.out.println(ex.toString());
	  ex.printStackTrace();
	  return false;
	}
 }

    private void getServerReply() {
       Object obj = receive();
       String message;
       
       if(obj.equals("logoutOK")){
    	   this.gui.streamDisplay.append("Logout successful"); 
    	   this.gui.t1Flag = false;
    	   connected = false;
    	   this.gui.setLoggedOn(false);
     }
       else if(obj instanceof MusicStream){
    	   MusicStream ms; 
    	   ms = (MusicStream) obj;
    	   message = ms.musicVector.lastElement();
    	   System.out.println("In get server reply");
    	   this.gui.appendMessage("\n" + message);
   // 	   this.gui.musicStrm.musicVector.addElement(message);
    	   System.out.println("CT Vector size " + this.gui.musicStrm.musicVector.size());
    	   this.gui.count++;
    	   System.out.println("Count : " + this.gui.count);
    	   
    	   for(int i=0; i<this.gui.musicStrm.musicVector.size();++i){
    		   System.out.println("Element " + i + " is " + 
    				   this.gui.musicStrm.musicVector.elementAt(i));
    	   }
       }
       else if(obj instanceof FootballStream){
    	   FootballStream fs; 
    	   fs = (FootballStream) obj;
    	   message = fs.footyVector.lastElement();
    	   System.out.println("In get server reply, footyVector.size() : " + fs.footyVector.size());
    	   this.gui.appendMessage("\n" + message);
    	   for(int i=0; i<this.gui.footyStrm.footyVector.size();++i){
    		   System.out.println("Element " + i + " is " + 
    				   this.gui.footyStrm.footyVector.elementAt(i));
    	   }
       }
       
   /*    if (message != null){
    	   this.gui.appendMessage("\n" + message);
       }  */
       
 //      else System.out.println("Null object");
 //      }
    }
    
    
  public void messageTransmit(Object o){ 	
      Object obj = o; 
      
      if(connected == true){    	  
    	if(obj instanceof FootballStream){
    		FootballStream fs = (FootballStream) obj;
    		 try{            
    	    		System.out.println("About to transmit FootballStream object");
    	    	    os.writeObject(fs);
    	    	    os.flush();
    	    	    this.getServerReply();
    	    	 }
    	    	     
    	         catch (Exception ex){ 
    	    	   ex.printStackTrace();
    	         }
    	}	   		
    	else if(obj instanceof MusicStream){
    			 MusicStream ms = (MusicStream) obj;   		
    		 try{            
    	    		System.out.println("About to transmit MusicStream object");
    	    	    os.writeObject(ms);
    	    	    os.flush();
    	    	    this.getServerReply();
    	    	 }   	    	     
    	         catch (Exception ex){ 
    	    	   ex.printStackTrace();
    	         }
    	}
    	else if(obj.equals("logout")){
    		 
    		try{            
	    		System.out.println("About to try logout");
	    	    os.writeObject("logout");
	    	    os.flush();
	    	    this.getServerReply();
	    	 }   	    	     
	         catch (Exception ex){ 
	    	   ex.printStackTrace();
	         }
    		
    	}
      }
    	else this.gui.appendMessage("Please login to server first!!");   	    	
    } 

    private Object receive() 
    {
	Object o = null;
	try 
        {
	   o = is.readObject();
	} 
        catch (Exception ex) 
        {
	   System.out.println(ex.toString());
	}
	return o;
    }     
}

******************** Server **********************

import java.net.*;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Panel;
import java.awt.event.*;
import java.io.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class Server extends JFrame implements ActionListener, Runnable
{
	protected static StreamService ss;    //Create StreamService object
	private static String clients[] = new String[20];
	protected static int clientCount;
		
/********************** ServerGUI code ***************************/
	   private HandleConnectionThread con;	
	   private 	JButton  startButton;
	   private 	JButton  stopButton;
	   private static   JTextField onlineCount;
	   private JLabel displayLabel;
	   JTextArea display;
	   private JScrollPane scroll;
	   private JPanel middlePanel;
	   private JPanel topPanel;
	   private static Thread t1;
	   
	   public Server() {		   
	        super("ServerGUI");
		    topPanel = new JPanel();
		    middlePanel = new JPanel();
	        
	        startButton = new JButton("Start Server");
	        startButton.setBackground(Color.white);
	        startButton.addActionListener(this);
	        
	        stopButton = new JButton("Stop Server");
	        stopButton.addActionListener(this);
	        
	        onlineCount = new JTextField("Users:", 10);
	        
	        displayLabel = new JLabel("Display");
	        
	        display = new JTextArea(7, 30);
	        display.setLineWrap(true);
	        scroll = new JScrollPane(display, 
	        		ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	        		ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	        	        
	        topPanel.add(startButton);
	        topPanel.add(stopButton);
	        topPanel.add(onlineCount);
	        
	        middlePanel.add(displayLabel);
	        middlePanel.add(scroll);

	        this.add(topPanel, BorderLayout.NORTH);
	        this.add(middlePanel, BorderLayout.CENTER);

	        this.setSize(400, 400);
	        this.setVisible(true);
	        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	    } 
	
	   public void actionPerformed(ActionEvent e) {

			System.out.println("Action Event");

			   if 
				(e.getSource() == startButton) {
				 display.append("Start button pressed.");
				 System.out.println("Start button pressed");
				 t1.start();				 
			   }			   			 
			     else if
				  (e.getSource() == stopButton){			  
				   display.append("Stop button pressed.");
				   System.out.println("Stop button pressed");
			     }	

			   }   
			
 //   public void startServer()
	   public void run()
    {
        ServerSocket serverSocket = null;
        try 
        {
            serverSocket = new ServerSocket(5050);
            System.out.println("Server has started listening on port 5050");
            display.append("Server has started listening on port 5050");
        } 
        catch (IOException e) 
        {
        	System.out.println("Error: Cannot listen on port 5050: " + e);
        	display.append("Error: Cannot listen on port 5050: " + e);
            System.exit(1);
        }
        
        while (true) // infinite loop - loops once for each client
        {
            Socket clientSocket = null;
            try 
            {
                clientSocket = serverSocket.accept();  // returns
           //     setClientCount(getClientCount() + 1);
                clientCount++;
                display.append("Server has just accepted socket connection from a client " + 
                		clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
                System.out.println("Server has just accepted socket connection from a client " + 
                		 clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
                display.append("ServerClass: Client count is :" + Integer.toString(clientCount));
                System.out.println("ServerClass: Client count is :" + Integer.toString(clientCount));
                onlineCount.setText("Users:" + Integer.toString(clientCount));
            } 
            catch (IOException e) 
            {
            	display.append("Accept failed: 5050 " + e);
                break;
            }	

	       // Create the Handle Connection object - only create it
            ss = new StreamService();
            con = new HandleConnectionThread(clientSocket, ss, this);
            System.out.println("Con : " + con);
        //    con2 = new HandleConnectionThread(clientSocket, this);
            

            if (con == null) //If it failed send and error message
            {
                try 
                {
                    ObjectOutputStream os = new ObjectOutputStream(clientSocket.getOutputStream());
                    os.writeObject("error: Cannot open socket thread");
                    os.flush();
                    os.close();
                } 
                catch (Exception ex)  //failed to even send an error message
                {
                	display.append("Cannot send error back to client:  5050 " + ex);
                }
            }
            else {
            	con.start();
            }
        }
        try  // do not get here at the moment 
        {
        	System.out.println("Closing server socket");
        	display.append("Closing server socket.");
            serverSocket.close();
        } 
        catch (IOException e) 
        {
        	display.append("Could not close server socket. " + e.getMessage());
        }
    }
public static void main(String[] args) {
	
	t1 = new Thread(new Server());

	}
}

************************* HandleConnection **********************
/*// The Handle connection class - that deals will all client requests directly
// by Derek Molloy

import java.net.*;
import java.io.*;
import java.util.*;


public class HandleConnection
{

    private Socket clientSocket;			// Client socket object
    private ObjectInputStream is;			// Input stream
    private ObjectOutputStream os;			// Output stream
    
    // The constructor for the connecton handler

    public HandleConnection(Socket clientSocket) 
    {
        this.clientSocket = clientSocket;
    }

    // The main execution method 

    public void init() 
    {
        String inputLine;

        try 
        {
            this.is = new ObjectInputStream(clientSocket.getInputStream());
            this.os = new ObjectOutputStream(clientSocket.getOutputStream());
            while (this.readCommand()) {}

         } 
         catch (IOException e) 
         {
                e.printStackTrace();
         }
    }

    // Receive and process incoming command from client socket 

    private boolean readCommand() 
    {
        Object obj = null;

        try 
        {
            obj = is.readObject();
            System.out.println("Shape converted to string = " + obj.toString());
        } 
        catch (Exception e) 
        {
            obj = null;
        }
        if (obj == null) 
        {
            this.closeSocket();
            return false;
        }
        
        return true;

    }
        

    private void send(Object o) 
    {
        try 
        {
            System.out.println("Sending " + o);
            this.os.writeObject(o);
            this.os.flush();
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
    
    // Send a pre-formatted error message to the client 
    public void sendError(String msg) 
    {
        this.send("error:" + msg);	//remember a string IS-A object!
    }
    
    // Close the client socket 
    public void closeSocket()		//close the socket connection
    {
        try 
        {
            this.os.close();
            this.is.close();
            this.clientSocket.close();
        } 
        catch (Exception ex) 
        {
            System.err.println(ex.toString());
        }
    }

}

*/

// The Handle connection class - that deals will all client requests directly
// by Derek Molloy

import java.net.*;
import java.io.*;
import java.util.*;

public class HandleConnectionThread extends Thread
{
    protected FootballStream fs;
    private Socket clientSocket;			// Client socket object
    private ObjectInputStream is;			// Input stream
    private ObjectOutputStream os;
    private StreamService streamService;
    private String clients[] = new String[20];
	private Server server;

    public HandleConnectionThread(Socket clientSocket, StreamService ss, Server server) 
    {
    	System.out.println("In handle connection constructor");
    	this.streamService = ss;
    	this.server = server;
    	this.clientSocket = clientSocket;
        System.out.println("Client count is : " + this.server.clientCount);
        // init();
    }
    
 /*   public HandleConnectionThread(Socket clientSocket, Server server) 
    {
    	System.out.println("In handle connection constructor");
        this.server = server;
        clientCount++;
        System.out.println("Client count is : " + clientCount);
        // init();
    }   */

    // The main execution method 
    public void run() 
    {
//        String inputLine;
        System.out.println("Got to run()");

        try 
        {
        	System.out.println("Got to try");
            this.is = new ObjectInputStream(clientSocket.getInputStream());
            this.os = new ObjectOutputStream(clientSocket.getOutputStream());                      
            while (this.readCommand()) {}

         } 
         catch (IOException e) 
         {
                e.printStackTrace();
         }
    }


    private boolean readCommand() 
    {
       Object obj = null;

        try 
        {
            obj = is.readObject();
            System.out.println("is.readObject()" + obj);
            
            if(obj.toString().equals("logout")){
            	this.sendReply((Object) "logoutOK");
            	this.closeSocket();
            }
            
            if(obj instanceof FootballStream){
            	System.out.println(obj.getClass());
    //        	sendReply(obj);
            	fs = (FootballStream) obj;
            	sendReply(fs);
            	streamService.addFootyMessage(fs);
            	System.out.println("Username " + fs.getUsername());
            	System.out.println("In handle connection, first and last element of received vector are " + 
            			fs.footyVector.firstElement() + " and " + fs.footyVector.lastElement());
            }
            else if(obj instanceof MusicStream){
            	System.out.println(obj.getClass());
            	sendReply(obj);
            	MusicStream ms = (MusicStream) obj;
            	streamService.addMusicMessage(ms);
            	System.out.println("ms.text : " + ms.getText());
            	System.out.println("Username: " + ms.getUsername());
            	System.out.println("In handle connection, first and last element of received " +
            			"vector are " + ms.musicVector.firstElement() + " and " + ms.musicVector.lastElement());
            }           
        } 
        catch (Exception e) 
        {
        	System.out.println("In readCommand() exception");
            obj = null;
         //   e.printStackTrace();
            
        }
        if (obj == null) 
        {
        //    this.closeSocket();
            return false;
        }
        
        return true;

    }
        
   private void sendReply(Object o) 
    {
        try 
        {        	
            this.os.writeObject(o);
            this.os.flush();
            System.out.println("Reply sent to client.");
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
    
   public void closeSocket()		//close the socket connection
    {
        try 
        {
        	System.out.println("About to close client socket..");
            this.os.close();
            System.out.println("Here 1");           
            this.is.close();
            System.out.println("here 2");
            this.clientSocket.close();
            System.out.println("here 3");
            System.out.println("Client count 1 : " + this.server.clientCount);
            this.server.clientCount--;
            System.out.println("Client count 2 : " + this.server.clientCount);
        } 
        catch (Exception ex) 
        {
            System.err.println("This error " + ex.toString());
        }
    }

}

Open in new window

0
oggiemcAuthor Commented:
I think i may have found the problem..Please ignore question for now..
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

oggiemcAuthor Commented:
i fixed the username issue..But im still having a problem whereby the server side seems to be only storing the first vector element..on line 786 above it is printing out the first element twice instead of the first and last elements..Any ideas?
0
oggiemcAuthor Commented:
just to elaborate..On the clients side, i can add strings to my vector no problem and the vector populates the data ok.. But when i send the object to the server and try to access the vector size, it is always only one element even though i am continuously adding elements on the client side. for instance if i add the following line after line 782 above:

System.out.println("Vector size " + ms.musicVector.size());

The output is always 1???????????
0
gordon_vt02Commented:
General comment, likely unrelated to the problem:

You've got at least one class extending Thread, which is usually considered a "bad" practice.  You are better off implementing the Runnable interface and then wrapping that in a Thread or providing it to an Executor.  Did you have a particular reason for subclassing Thread, or was it just to achieve multi-threading.

-- On a more relevant note, if your Vectors are not synchronizing properly between client and server, is it possible there is a race condition or other multi-threading issue going on?  Is it possible for one or more clients to send multiple updates to the server simultaneously?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
oggiemcAuthor Commented:
Hi gordon,

The only class to i see sextending thread above is HandleConnectionThread..

I dont believe vector problem is related to race condidtion.. Im only using one client at the moment.. I got an answer from stackoverflow which i believe is correct:

http://stackoverflow.com/questions/8569817/tcp-client-server/8569917#8569917
0
gordon_vt02Commented:
Yep.  That definitely looks like the problem you're seeing.  Didn't realize that about ObjectOutputStream.  That's good to know!
0
oggiemcAuthor Commented:
yeah..im going to have to look at that reset method i think because im going to have to use it for my particular problem..
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

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.