0

We just started Network-Programming in School, and now i got a problem with my homework(im not the best programmer). So basically i got a Java Chatroom with 3 Classes. A ClientHandler that gets startet as a thread when a client connects to server, a servermain class, and a clientframe class where my gui is stored.

So everytime i connect to the server via terminal(with telnet localhost 10023) a new Thread of ClientHandler gets started and i can chat via terminal with other users. But how does the whole thing work with my gui ? Sry for my bad English btw. Serveclass:

 import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.TreeMap;


    public class Server {
        static Set<ClientHandler> clients = new HashSet<>();
        public static void broadcastMessage(String message) throws IOException {
            for(ClientHandler c:  clients) {
                if(!(clients.equals(c.username))) {
                    c.sendMessage(message);
                }
            }
        }

        private void startServer() {
            try(ServerSocket server = new ServerSocket(10023)) {
                while(true){
                    Thread thread = new Thread(new ClientHandler(server.accept()));
                    thread.start();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            new Server().startServer();
        }
    }

ClientHandler:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class ClientHandler implements Runnable {
    private Socket client = null;
    private Server server = null;
    BufferedReader reader = null;
    PrintWriter writer = null;
    public String username;
    public ClientHandler(Socket client) throws IOException {
        this.client = client;
        this.server = server;
        this.reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        this.writer = new PrintWriter(client.getOutputStream());
    }
    @Override
    public void run() {
        try {
            Server.clients.add(this);
            writer.println("Please enter your username: ");
            writer.flush();
            username = reader.readLine();
            try {
                while(true) {
                    String message;
                    message = reader.readLine();
                    if(!(message.trim().equals(""))) {
                        Server.broadcastMessage(message);
                    }
                }
            }catch(Exception e) {}
            writer.println("Verbindung geschlossen");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }

    public void sendMessage(String message) throws IOException {
        //ClientFrame.taChat.append(message);
        writer.println(username + ": " + message);
        writer.flush();
    }
}

And my ClientFrame:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.Socket;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class ClientFrame {

    static JFrame mainFrame;
    static JTextField tfMessage;
    static JTextArea taUser = new JTextArea();
    static JTextArea taChat = new JTextArea();
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ClientFrame window = new ClientFrame();
                    //Socket socket = new Socket("127.0.0.1", 10023);
                    window.mainFrame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * Create the application.
     */
    public ClientFrame() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        mainFrame = new JFrame();
        mainFrame.setTitle("ChatServer - Harisch");
        mainFrame.setBounds(200, 100, 450, 300);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);

        JPanel pSouth = new JPanel();
        mainFrame.getContentPane().add(pSouth, BorderLayout.SOUTH);
        pSouth.setLayout(new BorderLayout(0, 0));

        JButton bnDisconnect = new JButton("Disconnect");
        pSouth.add(bnDisconnect, BorderLayout.WEST);

        tfMessage = new JTextField();
        pSouth.add(tfMessage, BorderLayout.CENTER);
        tfMessage.setColumns(10);

        JButton bnSend = new JButton("Send");
        pSouth.add(bnSend, BorderLayout.EAST);

        JScrollPane spUser = new JScrollPane();
        mainFrame.getContentPane().add(spUser, BorderLayout.EAST);


        taUser.setEditable(false);
        taUser.setColumns(10);
        spUser.setViewportView(taUser);

        JScrollPane spChat = new JScrollPane();
        mainFrame.getContentPane().add(spChat, BorderLayout.CENTER);

        //      bnSend.addActionListener(new ActionListener() {
        //          
        //          @Override
        //          public void actionPerformed(ActionEvent arg0) {
        //              
        //              if(tfMessage.getText() != "") {
        //                  ServerMain.messages.put("test", tfMessage.getText());
        //              }
        //              
        //          }
        //      });

        taChat.setEditable(false);

    }

}
  • 1
    Don't make your variables static unless you know what you do. – Sam Jan 29 '14 at 13:04
  • I agree with @Sam. None of those fields should be static. Sorry, but this looks like you're trying to create a very complex program before learning basic Java. Learn first things first, like how to create basic well-behaved OOP compliant objects. – Hovercraft Full Of Eels Jan 29 '14 at 13:06
  • Like i said, I'm not the beste programmer ^^ I never really got this static thing and when to use it – user3248787 Jan 29 '14 at 13:09
  • See also this related [example](http://stackoverflow.com/a/3245805/230513). – trashgod Jan 29 '14 at 13:22
  • If you haven't got this "static thing" just don't use it. Never! You will get problems you can't explain and fix if you use it anyway. – Sam Jan 29 '14 at 13:24

1 Answers1

1

Your ClientFrame class just needs to do what you are using terminal for. It should open a socket to port 10023, then send text to it when the Send button is clicked. It should also listen for incoming messages and display them when received.

Mark Wagoner
  • 1,729
  • 1
  • 13
  • 20
  • Ok thanks :) But how do i do that ? I mean i know how to connect to the server with a socket but how do i listen for incoming messages ? – user3248787 Jan 29 '14 at 13:04
  • Before you start with your chat program you should try to code a simple client/server ping pong program. That means you have a client which connects to a server and sends a "ping" message. The server responds to every "ping" from every client with a "pong". If you can do that your chat program will no longer be a challenge. – Sam Jan 29 '14 at 13:20