为聊天程序GUI创建用户列表

时间:2015-04-30 17:48:40

标签: java

我有三个程序一起工作来建立一个聊天室。我有一个服务器,处理程序和客户端。我试图在GUI中有一个统一的在线用户列表,因此如果新客户加入聊天,他们仍然可以看到用户列表。此列表是GUI中的可见列表功能。我在聊天处理程序中创建了数组列表,但我不知道如何让列表出现在GUI中。请帮助我,我是初学者。

服务器代码:

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer{
  Socket s;
  ArrayList<ChatHandler>handlers;
  public ChatServer(){
try{
  ServerSocket ss = new ServerSocket(2020);
  handlers = new ArrayList<ChatHandler>();
  for(;;){
s = ss.accept();//wait for a new client to connect
new ChatHandler(s, handlers).start();// spawn a handler for client
  }
}catch(IOException ioe){
  System.out.println(ioe.getMessage());
}
  }
  public static void main(String[] args){
ChatServer tes = new ChatServer(); 
  }

}

处理程序代码:

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatHandler extends Thread{
  Socket s;
  BufferedReader br;
  PrintWriter pw;
  String temp;
  ArrayList<ChatHandler>handlers;
  String nickName;
  List<String> myList = new ArrayList<String>()

  public ChatHandler(Socket s, ArrayList<ChatHandler>handlers){
    this.s = s;
    this.handlers = handlers;
    this.nickName = nickName;
  }


  public void run(){
    try{
      handlers.add(this);// add myself to list
      br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      pw = new PrintWriter(s.getOutputStream(), true);
      temp = "";
      System.out.println("Enter a username: ");
      nickName = br.readLine();
      myList.add(nickName);
      System.out.println(nickName+" joined the chat!");
      while((temp = br.readLine()) != null){
        for (ChatHandler ch : handlers){// broadcast to all clients
             ch.pw.println(nickName+":"+" "+temp); //tell each handler in turn to send message to its client
    }
    System.out.println(temp);
      }
    }catch(IOException ioe){
      System.out.println(ioe.getMessage());      
    }finally{
      handlers.remove(this);//remove myself from list
    }
  }
}

客户代码:

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;

public class ChatFrame extends Frame{
    public ChatFrame(){
        setSize(500,500);
        setTitle("Chatting with myself");
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent we){
                System.exit(0);
            }
        });
        ChatPanel sp = new ChatPanel();
        add(sp, BorderLayout.CENTER);
        setVisible(true);
    }

    public static void main(String[] args){
        ChatFrame sf = new ChatFrame();
    }
}

class ChatPanel extends Panel implements ActionListener, Runnable{
    Thread t;
    TextField tf;
    TextArea ta;
    List lst;
    Button b;
    Socket s;
BufferedReader br;
PrintWriter pw;
String temp;
boolean connected;

public ChatPanel(){
    setLayout(new BorderLayout());
    tf = new TextField();
    tf.addActionListener(this);
    add(tf, BorderLayout.NORTH);
    ta = new TextArea();
    add(ta, BorderLayout.WEST);
    lst = new List();
    add(lst, BorderLayout.EAST);
    b = new Button("Connect");
    b.addActionListener(this);
    add(b, BorderLayout.SOUTH);
    //t = new Thread(this);
}


public void actionPerformed(ActionEvent ae){
    if((ae.getSource() == b) && (!connected)){
        try{
            s = new Socket("127.0.0.1", 2020);
            pw = new PrintWriter(s.getOutputStream(), true);
        }catch(UnknownHostException uhe){
            System.out.println(uhe.getMessage());
        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
        connected = true;
        t = new Thread(this);
        //b.setEnabled(false);
        b.setLabel("Disconnect");
        t.start();
    }else if((ae.getSource() == b) && (connected)){
        connected = false;
        try{
            s.close(); //no buffering so, ok
        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
        //System.exit(0);
        b.setLabel("Connect");
    }else{
        temp = tf.getText();
        pw.println(temp);
        tf.setText("");
    }
}
public void run(){
    try{
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        ta.append("Please enter a username"+"\n");
        while(((temp = br.readLine()) != null) && connected){
            ta.append(temp + "\n");
            temp = "";


    }}catch(IOException ioe){
        System.out.println(ioe.getMessage());

    }
}
}

1 个答案:

答案 0 :(得分:0)

您需要四种方法才能实现目标:(1)一个ArrayList来保存所有昵称。 (2)Accessor(getter)将您的昵称列表提取到GUI中。 (3)一个Mutator(Setter)添加到昵称数组上。 (4)如果与聊天断开连接,则从阵列中删除或更新昵称的方法。

概要;您需要在服务器代码中创建三个方法和一个List。您将根据需要在客户端代码中调用这些方法。只要您想从其外部访问其方法,您还需要一个Server实例。请参阅以下代码并作为参考。

//Adds nickname to myList
public void AddUserName(String name){
    myList.add(name);
}

//Removes disconnected nicknames from myList
public void RemoveUserName(String name){
    for( int i = 0; i < myList.size(); i++ ){
        if(myList(i) == name){
        myList.remove(i);
        }
    }
}

//Returns all nicknames in myList
public ArrayList getUsersOnline(){
    return usersOnline;
} 

因此,在您的客户端代码中,您将编写如下内容:cs.getUsersOnline();.您可能还需要遍历并附加到客户端的列表中。例如,见下文:

for(int i=0; i < myList.size(); i++){
    list.add(ArrayList(i));
}

我希望我能够提供帮助。