日期:2014-05-20  浏览次数:20853 次

Thread和Socket问题,通过TCP将多个线程通信,现在需要完成的是一个窗口发其它的窗口都能收到,请高手帮忙看看哪里出错了
Client端:
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.net.*;

public class ChatClient extends Frame {
TextField tf = new TextField();
TextArea ta = new TextArea();
Socket socket;
DataOutputStream dos = null;
DataInputStream dis = null;

public static void main(String[] args) {
new ChatClient().launchFrame();
}

public void launchFrame() {
add(tf, BorderLayout.SOUTH);
add(ta, BorderLayout.NORTH);
setLocation(200, 200);
setSize(400, 300);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
disconnected();
System.exit(0);
}
});
connected();
new Thread(new ReceThread()).start();
tf.addActionListener(new Monitor());
setVisible(true);

}

private class Monitor implements ActionListener {

public void actionPerformed(ActionEvent e) {
ta.setText( tf.getText() + "\n");
try {
dos.writeUTF(tf.getText());
dos.flush();
} catch (IOException e1) {

e1.printStackTrace();
}
tf.setText(null);
}
}

private void connected() {
try {
socket = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void disconnected(){
try {
socket.close();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

private class ReceThread implements Runnable{

public void run() {
try {
while(true){
String str = dis.readUTF();
ta.setText(ta.getText()+str);
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

}


Server端:
import java.io.FilterInputStream;
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
boolean start = false;
ServerSocket ss = null;
DataOutputStream dos = null;

ArrayList<Client> clients = new ArrayList<Client>();

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

public ChatServer() {
try {
ss = new ServerSocket(8888);
start = true;
} catch (IOException e1) {
e1.printStackTrace();
}
try {
start = true;
while (start) {
Socket s = ss.accept();
System.out.println("A socket connected");
Client c = new Client(s);
clients.add(c);
new Thread(c).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

class Client implements Runnable {
private Socket s;
private DataInputStream dis;
private boolean connected = false;

public Client(Socket s) {
this.s = s;
connected = true;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(String s) {
try {
dos.writeUTF(s);
} catch (IOException e) {
e.printStackTrace();
}
}

public void run() {
while (connected) {
try {
String str = dis.readUTF();