麻烦编写multiThread聊天程序

时间:2017-01-17 17:06:30

标签: multithreading

我正在写一个多线程聊天程序,我希望服务器连接到多个客户端,客户端可以与每个客户端通信并相互发送消息。我希望客户端的所有消息都对服务器可见,而且服务器可以向所有可见的客户端发送消息。我的程序只将服务器连接到一个客户端,他们可以发送消息。

package chatserver2;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
   // import all the class that you will need for functionailty

// extends jframe to develop gui's in java
public class Server2 {

    private static JTextField userInput; // 
    private static JTextArea theChatWindow; //
    private static ObjectOutputStream output; // stream data out
    private static ObjectInputStream input; // stream data in
    private static ServerSocket server;
    private static Socket connection; // socket means set up connetion between 2 computers
    private static JFrame frame;
    private static int n;

//Constructor
    public static void main(String[] args) throws IOException {

        Server2 obj = new Server2();
//        Socket sock=new Socket("localhost",6789);
        System.out.println("Hello 4");
        obj.RunServer();
        System.out.println("Hello 3");
        try {
            while (true) {
                System.out.println("Hello 2");

                Handler obj2 = new Handler();
                //Handler obj3=new Handler();
                obj2.start();
                System.out.println("Accepted connection from "
                        + connection.getInetAddress() + " at port "
                        + connection.getPort());

                n++;
                System.out.println("Count " + n);
            }
        } finally {
            connection.close();
        }

    }

    public Server2() {

        frame = new JFrame();
        userInput = new JTextField();
        userInput.setEditable(false); // set this false so you dont send messages when noone is available to chat
        // action event listener to check when the user hits enter for example
        userInput.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                sendMessage(event.getActionCommand()); // string entered in the textfield
                userInput.setText(""); // reset text area to blank again

            }
        }
        );
        // create the chat window
        frame.add(userInput, BorderLayout.NORTH);
        theChatWindow = new JTextArea();
        frame.add(new JScrollPane(theChatWindow));
        frame.setSize(300, 150);
        frame.setVisible(true);
    }

// run the server after gui created
    public void RunServer() {

        try {
            server = new ServerSocket(6789); // 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
            while (true) {

                try {
                    waitForConnection(); // wait for a connection between 2 computers 
                    setupStreams();  // set up a stream connection between 2 computers to communicate
                    whileChatting();  // send message to each other
                    // connect with someone and have a conversation
                } catch (EOFException eofException) {

                    showMessage("\n Server ended Connection");
                }
            }
        } catch (IOException ioException) {

            ioException.printStackTrace();
        }
    }

//Wait for a connection then display connection information
    private void waitForConnection() {

        showMessage("waiting for someone to connect to chat room....\n");
        try {
            connection = server.accept();
        } catch (IOException ioexception) {

            ioexception.printStackTrace();
        }
        showMessage("Now connected to" + connection.getInetAddress().getHostName());
        showMessage(" at port " + connection.getPort());

    }
    // stream function to send and recive data

    private void setupStreams() throws IOException {

        output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
        output.flush(); // move data away from your machine
        input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in

        // String message = "WAIT";
        // sendMessage(message);
        //showMessage("\n Connection streams are now setup \n");
    }

// this code while run during chat conversions
    private void whileChatting() throws IOException {

        String message = "WAIT ";
        sendMessage(message);
        allowTyping(true); // allow user to type when connection
        do {
            // have conversion while the client does not type end
            try {

                message = (String) input.readObject(); // stores input object message in a string variable
                showMessage("\n " + message);
                System.out.println("Message from Client " + message);
            } catch (ClassNotFoundException classnotfoundException) {

                showMessage("\n i dont not what the user has sent");
            }
        } while (!message.equals("CLIENT - END"));// if user types end program stops

    }

    private void closeChat() {

        showMessage("\n closing connections...\n");
        allowTyping(true);
        try {

            output.close(); // close output stream
            input.close(); // close input stream
            connection.close(); // close the main socket connection

        } catch (IOException ioexception) {

            ioexception.printStackTrace();
        }
    }

// send message to the client
    private void sendMessage(String message) {

        try {

            output.writeObject(message);
            output.flush(); // send all data out
            showMessage("\nServer - " + message);
            System.out.println("Message to client " + message);

        } catch (IOException ioexception) {

            theChatWindow.append("\n ERROR: Message cant send");
        }

    }

// update the chat window (GUI)
    private void showMessage(final String text) {

        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {

                        theChatWindow.append(text);

                    }
                }
        );

    }

// let the user type messages in their chat window
    private void allowTyping(final boolean trueOrFalse) {

        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {

                        userInput.setEditable(trueOrFalse);

                    }
                }
        );

    }

    public static class Handler extends Thread {

        private Socket connection;

        //  static private ServerSocket server;
        public Handler() {
            //  this.socket = socket;
            String message = "WAIT";

        }

        //connection = server.accept();
        public void run() {

            System.out.println("Connect" + Server2.connection);
            while (true) {

                try {
                    waitForConnection();
                    setupStreams();
                    whileChatting();
                } catch (IOException ex) {
                    Logger.getLogger(Server2.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }

        private void waitForConnection() {
            System.out.println("Heelo");
            showMessage("waiting for someone to connect to chat room....\n");
            System.out.println("server" + server);
            try {
                connection = server.accept();
            } catch (IOException ioexception) {

                ioexception.printStackTrace();
            }
            System.out.println("Connection" + connection);

            showMessage("Now connected to" + connection.getInetAddress().getHostName());
            showMessage("AT port" + connection.getPort());
        }

        private void setupStreams() throws IOException {

            output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
            output.flush(); // move data away from your machine
            input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
            showMessage("\n Connection streams are now setup \n");

        }

// this code while run during chat conversions
        private void whileChatting() throws IOException {

            String message = " You are now connected ";
            sendMessage(message);
            allowTyping(true); // allow user to type when connection
            do {
                // have conversion while the client does not type end
                try {

                    message = (String) input.readObject(); // stores input object message in a string variable
                    showMessage("\n " + message);
                } catch (ClassNotFoundException classnotfoundException) {

                    showMessage("\n i dont not what the user has sent");
                }
            } while (!message.equals("CLIENT - END"));// if user types end program stops

        }

        private void closeChat() {

            showMessage("\n closing connections...\n");
            allowTyping(true);
            try {

                output.close(); // close output stream
                input.close(); // close input stream
                connection.close(); // close the main socket connection

            } catch (IOException ioexception) {

                ioexception.printStackTrace();
            }
        }

// send message to the client
        static private void sendMessage(String message) {

            try {

                output.writeObject(message);
                output.flush(); // send all data out
                showMessage("\nServer - " + message);

            } catch (IOException ioexception) {

                theChatWindow.append("\n ERROR: Message cant send");
            }

        }

// update the chat window (GUI)
        static private void showMessage(final String text) {

            SwingUtilities.invokeLater(
                    new Runnable() {

                        public void run() {

                            theChatWindow.append(text);

                        }
                    }
            );

        }

// let the user type messages in their chat window
        private void allowTyping(final boolean trueOrFalse) {

            SwingUtilities.invokeLater(
                    new Runnable() {

                        public void run() {

                            userInput.setEditable(trueOrFalse);

                        }
                    }
            );

        }

    }

}

这是客户:

package chatserver2;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
   // import all the class that you will need for functionailty

// extends jframe to develop gui's in java
public class Client2 extends JFrame {

    private JTextField userInput; // 
    private JTextArea theChatWindow; //
    private ObjectOutputStream output; // stream data out
    private ObjectInputStream input; // stream data in

    private Socket connection; // socket means set up connetion between 2 computers

//Constructor
    public Client2() {

        super("My Chat Service");
        userInput = new JTextField();
        userInput.setEditable(false); // set this false so you dont send messages when noone is available to chat
        // action event listener to check when the user hits enter for example
        userInput.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                sendMessage(event.getActionCommand()); // string entered in the textfield
                userInput.setText(""); // reset text area to blank again

            }
        }
        );
        // create the chat window
        add(userInput, BorderLayout.NORTH);
        theChatWindow = new JTextArea();
        add(new JScrollPane(theChatWindow));
        setSize(300, 150);
        setVisible(true);
    }

// run the server after gui created






    public void RunServer() {

        try {
            connection = new Socket("localhost", 6789);// 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
            while (true) {

                try {
                    // wait for a connection between 2 computers 
                    setupStreams();  // set up a stream connection between 2 computers to communicate
                    whileChatting();  // send message to each other
                    // connect with someone and have a conversation
                } catch (EOFException eofException) {

                    showMessage("\n Server ended Connection");
                } finally {

                    closeChat();
                }
            }
        } catch (IOException ioException) {

            ioException.printStackTrace();
        }
    }

//Wait for a connection then display connection information
    // stream function to send and recive data
    private void setupStreams() throws IOException {

        output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
        output.flush(); // move data away from your machine
        input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
        showMessage("\n Connection streams are now setup \n");

    }

// this code while run during chat conversions
    private void whileChatting() throws IOException {

        String message = "";

        allowTyping(true); // allow user to type when connection
        do {
            // have conversion while the client does not type end
            try {

                message = (String) input.readObject(); // stores input object message in a string variable
                System.out.println("message " + message);
                if (message.equals("WAIT")) {
                    ServerSocket server2 = new ServerSocket(5000);
                    System.out.println("Hello");
                    message = "5000";
                    sendMessage(message);

                }
                System.out.println("From server " + message);

                showMessage("\n " + message);
            } catch (ClassNotFoundException classnotfoundException) {

                showMessage("\n i dont not what the user has sent");
            }
        } while (!message.equals("CLIENT - END"));// if user types end program stops

    }

    private void closeChat() {

        showMessage("\n closing connections...\n");
        allowTyping(true);
        try {

            output.close(); // close output stream
            input.close(); // close input stream
            connection.close(); // close the main socket connection

        } catch (IOException ioexception) {

            ioexception.printStackTrace();
        }
    }

// send message to the client
    private void sendMessage(String message) {

        try {

            output.writeObject(" - " + message);
            output.flush(); // send all data out
            showMessage("\nServer - " + message);

        } catch (IOException ioexception) {

            theChatWindow.append("\n ERROR: Message cant send");
        }

    }

// update the chat window (GUI)
    private void showMessage(final String text) {

        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {

                        theChatWindow.append(text);

                    }
                }
        );

    }

// let the user type messages in their chat window
    private void allowTyping(final boolean trueOrFalse) {

        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {

                        userInput.setEditable(trueOrFalse);

                    }
                }
        );

    }

    public static void main(String[] args) {
        Client2 obj = new Client2();
        obj.RunServer();
    }

}

0 个答案:

没有答案