如何在JTextArea中附加消息,说明特定用户在客户端服务器中处于联机或脱机状态

时间:2014-07-08 06:42:06

标签: java swing inputstream serversocket outputstream

我真的不知道我是怎么在我的应用程序中显示这个,因为我只是不知道我将要使用的确切代码是什么。我正在创建一个简单的聊天客户端服务器,其中两个或多个客户端可以在输入/输出流和serversocket的帮助下相互聊天。我想要做的是,在一个人登录后,它会在JtextArea中弹出一条消息,说某个人在线,如果该人关闭了该应用程序,则会向其他客户发送一条消息,说明某个人离线

这是ChatClient的代码,它将显示用于绘制消息的JtextArea,用于键入消息的JtextField和用于向发送回客户端的发送者发送消息的JButton。

JTextArea incoming;
JTextArea outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
static JFrame frame;
JButton send;
JPanel mainPanel;

 static String userName;


public void createAndShowGUI(){

frame = new JFrame("chat client");  
mainPanel = new JPanel();
mainPanel.setBackground(new Color(53,53,53));


incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy     (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);




//create GridBagLayout and GridBagConstraints for Layouting
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();

//assign gbl inside componentPanel
 mainPanel.setLayout(gbl);  


//for layouting  JTextArea
gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 1;

//add labelLogin in componentPanel
gbl.setConstraints(qScroller, gbc);
mainPanel.add(qScroller);   


//for layouting  JTextField
outgoing = new JTextArea();
outgoing.setLineWrap(true);
outgoing.setWrapStyleWord(true);
JScrollPane oScroller = new JScrollPane(outgoing);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);


 oScroller.setPreferredSize(new Dimension(500,60));


gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 1;
gbc.gridheight = 0;

//add labelLogin in componentPanel
gbl.setConstraints(oScroller, gbc);
mainPanel.add(oScroller);       



//instantiate JButton

send = new JButton("send");
send.addActionListener(new SendButtonListener());
send.setPreferredSize(new Dimension(48,60));
send.setBorder(BorderFactory.createEtchedBorder(1));
send.setBackground(new Color(248,181,63));
send.setFont(new Font("verdana",Font.BOLD,12));

gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridy = 5;
gbc.gridx = 1;
gbc.gridwidth = 2;
gbc.gridheight = 0;

gbl.setConstraints(send, gbc);
mainPanel.add(send);    




setUpNetworking();



//confirmation();



Thread readerThread = new Thread(new IncomingReader());

 readerThread.start();  



 frame.add(mainPanel);  
 frame.setSize(605, 355);
 frame.setVisible(true);
 frame.setResizable(false);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  






}//end createAndShowGUI



private void setUpNetworking() {
    try {
        sock = new Socket("00.000.00.00", 5000);    

        InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
        reader = new BufferedReader(streamReader);
        writer = new PrintWriter(sock.getOutputStream());
        System.out.println("network established");
    }
    catch(IOException ex)
    {

     // ex.printStackTrace();

      JOptionPane.showMessageDialog(null, "could not connect to server!","error", JOptionPane.ERROR_MESSAGE );  
      System.exit(0);   


    }
}


public String getUserName(){

return userName;

}

public void setUserName(String uname){


userName = uname;   

}

     //is this a right method...?

public void confirmation(){ 
writer.println(getUserName());
writer.flush(); 

    //System.out.print(getUserName() + " is online " + "\n");       
    //incoming.append(getUserName() + " is online " + "\n");
}




     public class SendButtonListener implements ActionListener {
     public void actionPerformed(ActionEvent ev) {

        try {

            writer.println(getUserName());
            writer.print(" : ");
            writer.println(outgoing.getText());
            writer.flush();





        }
        catch (Exception ex) {
            ex.printStackTrace();
        }

        outgoing.setText("");
        outgoing.requestFocus();
    }
}

 class IncomingReader implements Runnable {

    LoginForm lf = new LoginForm();

    public void run() {
        String message;
        String username;

        try {
            while ((username = reader.readLine()) != null) {
                    message = reader.readLine();

                   incoming.append(username + message + "\n");


                //if else here?

            }

        } catch (IOException ex)
        {

          ex.printStackTrace();
        }
    }
}



public static void main(String [] args){

new ChatClient().createAndShowGUI();



}//end main

  }//end class

下面是ChatServer,其中来自ChatClients的所有邮件都发送到ChatServer并再次发送回来,以便所有客户端都能阅读邮件。

public class ChatServer {

    String uname, userName, confirmation;

    ArrayList clientOutputStreams;

    public class ClientHandler implements Runnable {
        BufferedReader reader;
        Socket sock;

        public ClientHandler(Socket clientSOcket) {
            try {
                sock = clientSOcket;
                InputStreamReader isReader = new InputStreamReader(
                        sock.getInputStream());
                reader = new BufferedReader(isReader);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        public void run() {
            String message;

            try {

                // I wonder if the code below is right.?

                confirmation = reader.readLine();
                System.out.println(confirmation + " is online");

                while ((userName = reader.readLine()) != null) {
                    message = reader.readLine();

                    // System.out.print(userName);
                    // System.out.print(message + "\n");

                    tellEveryone(userName);
                    tellEveryone(message);

                }

            } catch (Exception ex) {

                System.out.println(confirmation + " is offline");

                // System.out.println("connection reset!");
                // ex.printStackTrace();

            }

        }

    }

    public static void main(String[] args) {
        new ChatServer().go();
    }

    public void go() {
        clientOutputStreams = new ArrayList();
        try {
            ServerSocket serverSock = new ServerSocket(5001);
            while (true) {
                Socket clientSocket = serverSock.accept();
                PrintWriter writer = new PrintWriter(
                        clientSocket.getOutputStream());

                // writer.println(confirmation);

                clientOutputStreams.add(writer);
                Thread t = new Thread(new ClientHandler(clientSocket));
                t.start();
                System.out.println("got a connection");

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void tellEveryone(String message) {
        Iterator it = clientOutputStreams.iterator();
        while (it.hasNext()) {
            try {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

0 个答案:

没有答案