带gui的多线程JavaChat

时间:2014-01-29 12:44:04

标签: java multithreading swing chat

我们刚刚在学校开始网络编程,现在我的作业出了问题(我不是最好的程序员)。 所以基本上我有一个带有3个类的Java聊天室。 ClientHandler,当客户端连接到服务器,servermain类和存储gui的clientframe类时,将startet作为线程获取。

所以每当我通过终端(使用telnet localhost 10023)连接到服务器时,一个新的ClientHandler线程就会启动,我可以通过终端与其他用户聊天。 但整个事情如何与我的gui一起工作? 因为我的英语不好而感到难过。 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();
    }
}

我的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 个答案:

答案 0 :(得分:1)

您的ClientFrame类只需要执行您使用终端的操作。它应该打开一个到端口10023的套接字,然后在单击“发送”按钮时向其发送文本。它还应该监听传入的消息并在收到消息时显示它们。