Avatar of oggiemc
oggiemc
Flag for Ireland asked on

ClientGUI locking up after transmitting one object

Hello all,
Im building a client server via Sockets.. I send objects over the network from client to server.. The problem is, after i send one object, when i try to send another one the clientGUI locks up.. I think it may have something to do with me not doing housekeeping on my outputStream in the ClientTransmit class?? Can someone have a look please? Thanks
************** 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 {
	public static final int defaultWidth = 80, defaultHeight = 40;
	
	   private String streamChoice;
	   
	   private FootballStream footyStrm;
	   private MusicStream musicStrm;
	   private String [] listChoices = {"Football", "Music"};
	   private JList streamSelect;
	   private List list;
	   
	   private Button  clearButton;
	   private Button  sendButton;
	   
	   private JTextArea messageInput;
	   private JScrollPane messageScroll;
	   
	   private 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();
	        
	        list = new List();
	        list.add("damian");
	        list.add("conor");
	        list.addActionListener(this);	       
	        
	        streamSelect = new JList(listChoices);
	        streamSelect.addListSelectionListener(
        			new ListSelectionListener(){
						public void valueChanged(ListSelectionEvent e) {							
							if (! e.getValueIsAdjusting()){
	                      //      System.out.println("here");
								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);
	        
	        clearButton = new Button("Clear");
	        clearButton.setBackground(Color.white);
	        clearButton.addActionListener(this);
	        
	        sendButton = new Button("Send");
	        sendButton.addActionListener(this);
	        
	        middleLabel = new JLabel("Enter text: ");
	        bottomLabel = new JLabel("Entered messages: ");
	        
	        topPanel.add(streamSelect);
	        topPanel.add(list);
	        topPanel.add(sendButton);	        
	        topPanel.add(clearButton);
	        middlePanel.add(messageScroll);
	        middlePanel.add(middleLabel, 0);	        
	        bottomPanel.add(streamPane);
	        bottomPanel.add(bottomLabel, 0);

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

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

 
@Override
 public void actionPerformed(ActionEvent e) {
	
	ClientTransmit ct = new ClientTransmit();
	String message = messageInput.getText();
	
	if(e.getSource()== sendButton){
		
		if(streamChoice.equals("football")){
			footyStrm = new FootballStream();
			footyStrm.footyVector.add(message);
	//		System.out.println("footy vector element 1 = " + 
	//				footyStrm.messageStream.firstElement());
	//		listElements(footyStrm);
			ct.messageTransmit(footyStrm);
		}
		
		else if(streamChoice.equals("music")){
			musicStrm = new MusicStream();
			musicStrm.musicVector.add(message);
	//		System.out.println("music vector element 1 = " + 
	//				musicStrm.musicVector.firstElement());	
			ct.messageTransmit(musicStrm);
		}
	}	
 }

 public String getStreamChoice(){
	 
	 String choice = null;
	
	if(streamSelect.getSelectedValue().equals("Football")){
		choice = "football";
		System.out.println("Football");
		return choice;
	}
	else{
		System.out.println("Music");
		choice = "music";
		return choice;
	}	
 }

************** 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;
    
    public ClientTransmit(){}

 
    public ClientTransmit(String 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());
	   System.out.print("Connected to Server\n");
	   return true;
	} 
        catch (Exception ex) 
        {
	  System.out.print("Failed to Connect to Server\n" + ex.toString());	
	  System.out.println(ex.toString());
	  ex.printStackTrace();
	  return false;
	}
 }

    private void getServerReply() 
    {
       System.out.println("In get server reply");
       String theReply; 
       theReply = (String) receive();
       if (theReply != null)
       {
	  System.out.println(theReply);
       }
    }
    
    public void messageTransmit(Object o){
    	
    	Object obj = o;
    	
    	if(connectToServer(localHost)){
    		
    	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();
    	         }
    		}
         }
    	    	
    }
	    
    public void sendMessage(Vector<String> m) {
    	String localhost = "127.0.0.1";
		String serverIP = localhost ;
    	Vector<String> message = m;   
    	
    	if(connectToServer(serverIP)){
	try 
        {
		System.out.println("About to transmit shape");
	    os.writeObject(message);
	    os.flush();
	    this.getServerReply();}
	     
        catch (Exception ex) 
        {
	   ex.printStackTrace();}
        }
    }
    

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

Open in new window

Java

Avatar of undefined
Last Comment
mccarl

8/22/2022 - Mon
CEHJ

Make sure the other end is actually continually reading what's being sent
oggiemc

ASKER
Yes, i have a while loop to continually read objects..
CEHJ

Put a timestamping debugging SOP in both ends and let me know what gets printed
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
oggiemc

ASKER
Sorry, have absolutely no idea what that means..
ASKER CERTIFIED SOLUTION
mccarl

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
oggiemc

ASKER
ok, thanks mccarl..Theres a few classes for the server..ServerGUI, Server (which accepts a connection and then offloads responsibility to the HandleConnection class)..Please see attached code
************ ServerGUI **************
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

import javax.swing.JFrame;

public class ServerGUI extends JFrame implements ActionListener {
	public static final int defaultWidth = 80, defaultHeight = 40;

	   private Button  startButton;
	   private Button  stopButton;
	   Server server = new Server();
	   
	   public ServerGUI() {
		   
	        super("ServerGUI");
		    Panel topPanel = new Panel();
	        
	        startButton = new Button("Start Server");
	        startButton.setBackground(Color.white);
	        startButton.addActionListener(this);
	        topPanel.add(startButton);
	        
	        stopButton = new Button("Stop Server");
	        stopButton.addActionListener(this);
	        topPanel.add(stopButton);

	        this.add(topPanel, BorderLayout.NORTH);
//	        this.add(c, BorderLayout.CENTER);

	        this.setSize(400, 400);
	        this.setVisible(true);
	        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	    }  
	 

public static void main(String[] args) {
    new ServerGUI();
}

 public void actionPerformed(ActionEvent e) {

	System.out.println("Action Event");
//	Object source = e.getSource();

	   if 
		(e.getSource() == startButton) {
		 System.out.println("Start button pressed.");
		server.startServer();}
	   
	 
	   else if
		  (e.getSource() == stopButton){			  
		   System.out.println("Stop button pressed.");
}	

}  } 
 

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

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

public class Server //extends ServerGUI
{
	protected static StreamService ss;    //Create WhiteboardService object
	private String clients[] = new String[20];
	private int clientCount = 0;
	
    public static void startServer()
    {
 //   	Enumeration e = null;
        ServerSocket serverSocket = null;
        try 
        {
            serverSocket = new ServerSocket(5050);
            System.out.println("Server has started listening on port 5050");
        } 
        catch (IOException e) 
        {
            System.out.println("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
                System.out.println("Server has just accepted socket connection from a client " + 
                		clientSocket.getInetAddress().getHostAddress() + " " + clientSocket.getPort());
            } 
            catch (IOException e) 
            {
                System.out.println("Accept failed: 5050 " + e);
                break;
            }	

	       // Create the Handle Connection object - only create it
            ss = new StreamService();
            HandleConnection con = new HandleConnection(clientSocket, ss );

            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
                {
                    System.out.println("Cannot send error back to client:  5050 " + ex);
                }
            }
            else { con.init(); } // otherwise we have not failed to create the HandleConnection object
				 // run it now.
        }
        try  // do not get here at the moment 
        {
            System.out.println("Closing server socket.");
            serverSocket.close();
        } 
        catch (IOException e) 
        {
            System.err.println("Could not close server socket. " + e.getMessage());
        }
    }
}

************** 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 HandleConnection
{

    private Socket clientSocket;			// Client socket object
    private ObjectInputStream is;			// Input stream
    private ObjectOutputStream os;
    private StreamService streamService;
    private String clients[] = new String[20];
	private static int clientCount = 0;

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

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

        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 
        {
       // 	System.out.println(obj.getClass());
            obj = is.readObject();
            System.out.println("is.readObject()");
            
            if(obj instanceof FootballStream){
            	System.out.println(obj.getClass());
            	sendReply(obj);
            	FootballStream fs = (FootballStream) obj;
            	streamService.addFootyMessage(fs);
            	System.out.println("In handle connection, first element of received vector is " + 
            			fs.footyVector.firstElement());
            }
            else if(obj instanceof MusicStream){
            	System.out.println(obj.getClass());
            	sendReply(obj);
            	MusicStream ms = (MusicStream) obj;
 //           	streamService = new StreamService();
            	streamService.addMusicMessage(ms);
 //           	System.out.println("In handle connection, first element of received vector is " + 
 //           			ms.musicVector.firstElement());
            }
            
            
    //        rc.shapeRepaint((Vector<Shape>) obj);
            
        } 
        catch (Exception e) 
        {
        	System.out.println("In 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();
            this.is.close();
            this.clientSocket.close();
        } 
        catch (Exception ex) 
        {
            System.err.println(ex.toString());
        }
    }

}

Open in new window

oggiemc

ASKER
I think the HandleConnection class will be the one causing the issue...
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
mccarl

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
oggiemc

ASKER
Hi mccarl,

Thanks for your detailed reply..With regards to your first point, i agree..Obviously i shouldnt be creating a new connection for each object..I will see about fixing that..
With regards to your second point, yes we actually have to make our application multi-threaded..Well, i will leave it for the night for now (its 2 in the morning!)..I will let you know how i get on tomorrow and points will be coming your way :)
oggiemc

ASKER
Hi mccarl,

I fixed the code so that the connectToServer() is only called once when the ClientTransmit is first instantatiated. Its working fine now. Thanks for your help. I will give you the points now.
mccarl

Good to hear that you are making progress!!
Your help has saved me hundreds of hours of internet surfing.
fblack61