We help IT Professionals succeed at work.
Get Started

vector returns an object after I pass a socket to it?

OwenMoriarty
OwenMoriarty asked
on
585 Views
Last Modified: 2013-12-22

Im tyring to a very basic threaded client server chat application,

My server app has a Vector to which I add each socket as each client connects.

I want each client to be updated as any one clinet sends a message, I thought the lines below would do it but no it's not happening, any pointers?
for(int i=0;i<vector.size();i++){
        connectToClient = (Socket) vector.elementAt(i);
        DataOutputStream osToClient = new DataOutputStream(connectToClient.getOutputStream());
        osToClient.writeUTF(conversation);
package chat;
import java.io.*;
import java.net.*;
import java.util.Vector;
 
public class server extends javax.swing.JFrame {
    
    
    public server() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 409, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new server().setVisible(true);
            }});
            try  {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);
 
      int clientNo = 1; // The number of a client
 
      while (true)   {
        // Listen for a new connection request
        Socket connectToClient = serverSocket.accept();
 
        // Print the new connect number on the console
        System.out.println("Start thread for client " + clientNo);
 
        // Find the client's host name, and IP address
        InetAddress clientInetAddress = connectToClient.getInetAddress();
        System.out.println("Client " + clientNo + "'s host name is " + clientInetAddress.getHostName());
        System.out.println("Client " + clientNo + "'s IP Address is "+ clientInetAddress.getHostAddress());
 
        HandleAClient thread = new HandleAClient(connectToClient);
        thread.start();
        // Start the new thread
        clientNo++;// Increment clientNo
      }
    }
    catch(IOException ex)  {
      System.err.println(ex);
    }
        
    }
    // Define the thread class for handling a new connection
}
class HandleAClient extends Thread {
  String conversation = "";
  private Socket connectToClient;
  Vector vector = new Vector(5,2);
 
  public HandleAClient(Socket socket)  {
    connectToClient = socket;
    vector.addElement(connectToClient);
  }
  /**Implement the run() method for the thread*/
    @Override
    public void run() {
    try   {
      // Create data input and output streams
        //http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html#later
      DataInputStream isFromClient = new DataInputStream(connectToClient.getInputStream());
     
 
      // Continuously serve the client
      while (true) {
   
        String chatIn = isFromClient.readUTF();
   
        conversation += "\n" + chatIn;
        System.out.println(conversation + "<----conver");
        for(int i=0;i<vector.size();i++){
        connectToClient = (Socket) vector.elementAt(i);
        DataOutputStream osToClient = new DataOutputStream(connectToClient.getOutputStream());
        osToClient.writeUTF(conversation);
        }
        
      }
    }
    catch(IOException ex) {
      System.err.println(ex);
    }
  }
    
    // Variables declaration - do not modify                     
    // End of variables declaration                   
    
}
#####################################
package chat;
 
import java.io.IOException;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class client extends javax.swing.JFrame {
    DataInputStream chatIn;
    DataOutputStream chatOut;
    String conv = "";
    
    public client() {
      //  try {
            initComponents();
            jButSend.setEnabled(false);
//            Socket connectToServer = new Socket("localhost", 8000);
//            chatIn = new DataInputStream(connectToServer.getInputStream());
//        } catch (UnknownHostException ex) {
//            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
 
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jToggleConDis = new javax.swing.JToggleButton();
        jButSend = new javax.swing.JButton();
        jTextnewChat = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Gill Sans MT", 0, 12)); // NOI18N
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        jToggleConDis.setText("Connect / Disconnect");
        jToggleConDis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleConDisActionPerformed(evt);
            }
        });
 
        jButSend.setText("Send");
        jButSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButSendActionPerformed(evt);
            }
        });
 
        jTextnewChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextnewChatActionPerformed(evt);
            }
        });
 
        jTextField1.setText("jTextField1");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(140, Short.MAX_VALUE)
                .addComponent(jToggleConDis)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButSend)
                .addGap(18, 18, 18)
                .addComponent(jTextnewChat, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jToggleConDis)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButSend)
                    .addComponent(jTextnewChat, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>
 
    private void jTextnewChatActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        // Delete this stub if possible....
}                                            
 
    private void jButSendActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            chatOut.writeUTF(jTextnewChat.getText());                                        
            conv = chatIn.readUTF();
            jTextArea1.setText(conv);
        } catch (IOException ex) {
            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    private void jToggleConDisActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try {
       if (jToggleConDis.isSelected()) {
           try {
                Socket connectToServer = new Socket("localhost", 8000);
                chatIn = new DataInputStream(connectToServer.getInputStream());
                chatOut = new DataOutputStream(connectToServer.getOutputStream());
                jButSend.setEnabled(true);
                jTextArea1.setText("Connected");
                } catch (UnknownHostException ex) {                                             
                    Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
                }
                }//end if
           else {
                chatIn.close();
                chatOut.close();
                jButSend.setEnabled(false);
                jTextArea1.setText("Dis - Connected");
                }
       
        } catch (IOException ex) {
            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //an arraylist or vector, store each socket of each client in a vector...
    //
    //
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new client().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify
    private javax.swing.JButton jButSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextnewChat;
    private javax.swing.JToggleButton jToggleConDis;
    // End of variables declaration
    
}

Open in new window

Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE