本人在用java做一个Socket的通信软件,为了课程设计,想模拟QQ那样,登陆后出现在即的好友列表,然后比如点一个好友的名字,就能出现聊天窗口与其聊天,首先给一段代码
public FriendList(String name, int id, String LoginId, String ip) {
initComponents();
this.name = name;
this.id = id;
this.LoginId = LoginId;
this.ip = ip;
BindList();
ServerSocket ss;
try {
ss = new ServerSocket(port);
while (true) {
client = ss.accept();
new ChatFrame(name, client).setVisible(true);
port++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
我想实现多用户聊天,但是当我把while(true)删掉,只能跟一个聊天,加上后,貌似可以多用户聊天,但是弹出的聊天窗口有一个就像死机了,什么东西都没有,另一个却好的,不知道是什么情况,求帮助啊,,分数好说,只要能解决,窗口那个类里面也用了线程,到底是什么情况啊。

解决方案 »

  1.   

    这个是登陆后显示好友列表的那个类得主要代码,一些无关的就不贴了。。
    public FriendList(String name, int id, String LoginId, String ip) {
    initComponents();
    this.name = name;
    this.id = id;
    this.LoginId = LoginId;
    this.ip = ip;
    BindList();
    ServerSocket ss;
    try {
    ss = new ServerSocket(port);
    while (true) {
    client = ss.accept();
    new ChatFrame(name, client).setVisible(true);
    port++;
    }
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } }private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String aname = jList1.getSelectedValue().toString();


    try {
    new ChatFrame(aname, new Socket(ip, port)).setVisible(true);
    } catch (UnknownHostException e) {
    System.out.println(e);
    e.printStackTrace();
    } catch (IOException e) {
    System.out.println(e);
    e.printStackTrace();}

    }接下俩是聊天窗口的那个类得主要代码。。
    public ChatFrame(String name, Socket socket) {
    initComponents();
    this.name = name;
    this.socket = socket;
    this.thread = new Thread(this);
    this.thread.start();
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    this.cout.println(name + "说:" + jTextArea1.getText());
    jTextArea2.append("我说:" + jTextArea1.getText() + "\n");
    jTextArea1.setText("");
    } public void run() {
    try {
    this.cout = new PrintWriter(socket.getOutputStream(), true);
    this.cout.println(name);
    BufferedReader cin = new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    String name = cin.readLine();
    this.setTitle(name);
    String aline = cin.readLine();
    while (aline != null) {
    jTextArea2.append(aline + "\r\n");
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    aline = cin.readLine();
    }
    cin.close();
    cout.close();
    socket.close(); } catch (IOException e) {
    System.out.println(e);
    e.printStackTrace();
    }
    }
      

  2.   

    既然能实现和一个人聊天,客户端当然没得问题。关键是服务器。  你服务器while(true)了,那么这个线程就会一直在等待新的用户加入,捕获新的socket,所以服务器的线程一直会卡在哪里,服务器线程卡了,占用了系统资源,聊天界面就不能重绘了,所以才像会卡屏的。
      

  3.   

    当你上线时就用UDP 发上线的提示  好友那边 更新你的状态
    下线一样!!