Question

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;
    }

}
Was it helpful?

Solution

It looks like you are opening up a new connection every time in messageTransmit (via invoking connectToServer) but you are never closing that connection. I am not sure if that would cause the blocking that you are experiencing, but it is something that you should fix.

Either you want to keep your connection open and reuse it, in which case you should have a checkConnection method that checks if the current connection is still open, and if not, then opens one; or you want to open a new connection every time, in which case you should close your connection once you have finished receiving a response from the server.

As for the blocking, that can also happen if the send buffer for your TCP connection is full. The call to os.writeObject and/or os.flush can block if the OS send buffer is full. To de-couple this you should use an NIO framework such as Netty (or at least a queue and separate thread) for your message sending. You may want to verify on your server what data it is receiving to see if this is causing your blocking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top