本人在用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)删掉,只能跟一个聊天,加上后,貌似可以多用户聊天,但是弹出的聊天窗口有一个就像死机了,什么东西都没有,另一个却好的,不知道是什么情况,求帮助啊,,分数好说,只要能解决,窗口那个类里面也用了线程,到底是什么情况啊。
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)删掉,只能跟一个聊天,加上后,貌似可以多用户聊天,但是弹出的聊天窗口有一个就像死机了,什么东西都没有,另一个却好的,不知道是什么情况,求帮助啊,,分数好说,只要能解决,窗口那个类里面也用了线程,到底是什么情况啊。
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();
}
}
下线一样!!