求解一个简单问题
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class Dr{
public static void main(String[] args)throws Exception{
new winbox();
}}
class winbox extends JFrame implements ActionListener{
Button bu;
public winbox(){
bu=new Button("b");
add(bu);
bu.addActionListener(this);
//ChatClient cc = new ChatClient();//放这正常
// cc.receive();
setResizable(false);
setBounds(120,125,220,150);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
ChatClient cc = new ChatClient();//这里有问题
cc.receive();
}
}
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ChatClient {
/*public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.receive();
}*/
JTextField jtf;
JTextArea jta;
Socket s;
PrintWriter out;
BufferedReader in;
public ChatClient() {
JFrame frame = new JFrame("ChatClient");
frame.setSize(400, 300);
jta = new JTextArea();
jta.setEditable(false);
jtf = new JTextField();
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
send();
}
});
frame.getContentPane().add(new JScrollPane(jta));
frame.getContentPane().add(jtf, "South");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
s = new Socket("127.0.0.1", 9000);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void receive() {
while (true) {
try {
String text = in.readLine();
this.jta.append(text + "\n");
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
public void send() {
String text = this.jtf.getText();
this.jtf.setText("");
out.println(text);
out.flush();
}
}
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000);
LinkedList<Socket> list = new LinkedList<Socket>();
while (true) {
Socket s = ss.accept();
list.add(s);
Thread t = new ServerThread(s, list);
t.start();
}
}
}
class ServerThread extends Thread {
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list) {
this.s = s;
this.list = list;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
String str = in.readLine();
if (str == null)
return;
Iterator it = list.iterator();
while (it.hasNext()) {
Socket socket = (Socket) (it.next());
PrintWriter o = new PrintWriter(socket.getOutputStream());
o.println(str);
o.flush();
}
} catch (IOException e) {
return;
}
}
}
}
----------------解决方案--------------------------------------------------------