Results 1 to 4 of 4
  1. #1
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

    Default [SOLVED]Java Message Server/Client help

    All right I am writing a message server and client but I am having some trouble after the client sends a message the socket closes for some reason without any warning or exceptions being thrown I am not that experienced at network programming so any advice is greatly appreciated source files are below.

    Thanks in Advance,

    Sari

    Server:

    main.java

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    
    class Client {
    
        private PrintWriter out = null;
        private BufferedReader in = null;
        private Socket csock = null;
    
        public Client(Socket s) {
            csock = s;
        }
    
        public boolean SendMessage(String mes)
            throws IOException {
            if (!csock.isClosed()) {
                try {
                    out = new PrintWriter(csock.getOutputStream());
                    out.println(mes);
                    out.flush();
                    out.close();
                }   catch (IOException ioe) {
                    ioe.printStackTrace();
                    return false;
                }
            } else {
                throw new IOException("Socket closed");
            }
            return true;
        }
    
        public String ReceiveMessage() 
            throws IOException {
    
            String mes = "";
            StringBuffer MessageContents = new StringBuffer();
            if (!csock.isClosed()) {
                try {
                    in = new BufferedReader(new InputStreamReader(csock.getInputStream()));
                    while (mes != null) {
                        mes = in.readLine();
                        if (mes == null)
                            break;
                        MessageContents.append(mes);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    try {
                        csock.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
    
            } else {
                throw new IOException("Socket Closed");
            }
           return MessageContents.toString();
        }
    
    }
    
    class MessageServer {
    
        public static void main(String args[]) {
            ServerSocket sock = null;
            if (args.length < 1) {
                System.out.println("Usage: MessageServer <port>");
                System.exit(0);
            }
    
            System.out.println("\t\t**********Welcome to Java Message Server**********");
            System.out.println("\n\nBinding Socket...");
            try {
                 sock = new ServerSocket(Integer.parseInt(args[0]));
            } catch (Exception e) {
                System.out.println("Unable to Bind Socket:");
                e.printStackTrace();
                System.exit(1);
            }
            System.out.println("Socket Bound Waiting for Clients....");
            boolean started = false;
            Router rout = new Router();
            while (true) {
                try {
                    Socket s = sock.accept();
                    rout.addClient(s);
                    if (!started) {
                        rout.start();
                        started = true;
                    }
                    System.out.println("Client Connected From: " + s.getRemoteSocketAddress().toString());
                } catch (IOException ioe) {
                    System.exit(0);
                }
            }
        }
    
    }
    
    
    class Router
            extends Thread {
    
        private Vector<Client> clients = new Vector();
        public StringBuffer tosend = new StringBuffer();
    
        public Router() { }
    
        public void updateClients(Vector<Client> s) {
            clients = s;
        }
    
        public void addClient(Socket s) {
            clients.add(new Client(s));
        }
    
        @Override //used for netbeans
        public void run() {
            int x;
            while (true) {
                if (clients.size() == 0) {
                    continue;
                }
                x = 1;
                while (x  <= clients.size()) {
                    Client cur = clients.get(x - 1);
                    try {
                        tosend.append(cur.ReceiveMessage());
                    } catch (Exception e) {
                        clients.remove(x - 1);
                    }
                    x++;
                }
    
                x = 1;
    
                while (x  <= clients.size()) {
                    Client cur = clients.get(x - 1);
                    if (tosend.toString() != null || !tosend.toString().equals("")) {
                        try {
                            cur.SendMessage(tosend.toString());
                        } catch (Exception e) {
                            clients.remove(x - 1);
                        }
                    }
    
                    x++;
                }
                if (tosend.toString() != null || !tosend.toString().equals("")) {
                    System.out.println("Sending the following to all clients: " + tosend.toString());
                }
    
                tosend = new StringBuffer();
                tosend.append("");
            }
        }
    }
    Client:

    Java Code:
    package messageclient;
    
    import java.awt.event.*;
    
    public class ClientGUI
            extends javax.swing.JFrame
                implements KeyListener{
    
    
        public CommunicationClass comm = null;
    
        private MessageListener listener;
        public ClientGUI() {
            initComponents();
            this.setVisible(true);
            jTextArea1.setEditable(false);
            jPanel1.addKeyListener(this);
    
        }
    
    
        public void keyTyped(KeyEvent e) {
            if (e.getKeyCode() == e.VK_ENTER) {
                comm.SendMessage(jTextField2.getText() + ": " + jTextField1.getText());
                jTextField1.setText("");
            }
        }
    
        public void keyPressed(KeyEvent e) { }
    
        public void keyReleased(KeyEvent e) { }
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jTextField2 = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            host = new javax.swing.JTextField();
            jLabel4 = new javax.swing.JLabel();
            port = new javax.swing.JTextField();
            jButton2 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Java Message Client");
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
    
            jButton1.setText("Send");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jLabel1.setText("Message:");
    
            jLabel2.setText("Name:");
    
            jLabel3.setText("Host:");
    
            jLabel4.setText("Port:");
    
            jButton2.setText("Set Host/Port");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(7, 7, 7)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(24, 24, 24)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel3)
                    .addGap(3, 3, 3)
                    .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(port, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1))
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
    
            pack();
        }// </editor-fold>//GEN-END:initComponents
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
            comm = new CommunicationClass(host.getText(), Integer.parseInt(port.getText()));
            listener = new MessageListener(comm, jTextArea1);
            listener.start();
            String s = listener.getCurrentMessage();
        }//GEN-LAST:event_jButton2ActionPerformed
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
          try {
            listener.sleep(250);
            comm.closeIn();
          } catch (Exception e) { }
          comm.SendMessage(jTextField2.getText() + ": " + jTextField1.getText());
          comm.reopenIn();
          jTextField1.setText("");
        }//GEN-LAST:event_jButton1ActionPerformed
    
    
    
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JTextField host;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField port;
        // End of variables declaration//GEN-END:variables
    
    }
    CommunicationClass.java

    Java Code:
    package messageclient;
    
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    
    
    
    public class CommunicationClass {
    
        private Socket sock = null;
        private PrintWriter out = null;
        private BufferedReader in = null;
        public String host = null;
        public int port =  0;
    
        public CommunicationClass(String hos, int por) {
            host = hos;
            port = por;
            try {
                sock = new Socket(host, port);
                in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            } catch (IOException ioe) {
                System.err.print(ioe.getStackTrace());
                try {
                    sock.close();
                } catch (Exception e) {
                    System.err.print(e.getStackTrace().toString());
                    System.exit(1);
                }
            }
        }
    
        public void closeIn() {
            try {
                in.close();
            } catch(Exception e) { }
        }
    
        public void reopenIn() {
            try {
                in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            } catch(Exception e) { }
        }
    
        public boolean SendMessage(String mes) {
            try {
                out = new PrintWriter(sock.getOutputStream());
                out.println(mes);
                out.flush();
                out.close();
            } catch (IOException ioe) {
                System.err.print(ioe.getStackTrace().toString());
                return false;
            }
    
            return true;
        }
    
        public String ReceiveMessage() {
            String mes = "";
            StringBuffer MessageContents = new StringBuffer();
            try {
                while (mes != null) {
                    mes = in.readLine();
                    if (mes == null)
                        break;
                    JOptionPane.showMessageDialog(null, mes);
                    MessageContents.append(mes);
                }
            } catch (IOException ioe) {
                System.err.print(ioe.getStackTrace().toString());
                try {
                    sock.close();
                } catch (Exception e) {
                    System.err.print(e.getStackTrace().toString());
                }
            }
            return MessageContents.toString();
        }
    }
    MessageListener.java

    Java Code:
    package messageclient;
    
    import javax.swing.*;
    
    public class MessageListener
        extends Thread {
    
        private CommunicationClass comm = null;
        private StringBuffer mes = new StringBuffer();
        private String CurrentMessage = "";
        private JTextArea jtex = null;
    
        public MessageListener(CommunicationClass ncomm, JTextArea jte) {
            comm = ncomm;
            jtex = jte;
        }
    
    
        public void run() {
            try {
    
            } catch (Exception e) { }
            while (true) {
                try {
                    
                } catch (Exception e) {
                    System.err.print(e.getStackTrace().toString());
                }
                String s = comm.ReceiveMessage();
                jtex.append(s);
            }
        }
    
        public final String getCurrentMessage() {
            return CurrentMessage;
        }
    }
    Last edited by sari; 03-21-2010 at 02:26 AM.
    If you don't try you can't succeed.

  2. #2
    FallenBlade is offline Member
    Join Date
    Mar 2010
    Posts
    31
    Rep Power
    0

    Default

    I'm having the exact same problem, as I stated in my thread. It seems to me that the out.close(), shuts the socket.

    Can anyone explain this?

    Going to look up the .close() method in a bit more detail.

  3. #3
    FallenBlade is offline Member
    Join Date
    Mar 2010
    Posts
    31
    Rep Power
    0

    Default

    Taken from here:
    Does closing the BufferedReader/PrintWriter close the socket connection? - Stack Overflow

    Closing any stream readers/writers, closes the socket.

  4. #4
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

Similar Threads

  1. Java Server Client with database
    By cliff in forum Networking
    Replies: 2
    Last Post: 02-09-2010, 12:17 AM
  2. send message from a client to another client
    By esko in forum Networking
    Replies: 2
    Last Post: 02-04-2010, 08:21 PM
  3. Java Server, Flash Client
    By matbuckland in forum New To Java
    Replies: 3
    Last Post: 09-01-2009, 10:58 AM
  4. java server-client comm
    By Manas Das in forum Networking
    Replies: 2
    Last Post: 01-28-2009, 05:58 PM
  5. Java Server & C# client communicating through sockets
    By yukijocelyn in forum Networking
    Replies: 0
    Last Post: 09-05-2008, 11:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •