//客户端部分
importjava.awt.BorderLayout;importjava.awt.Frame;importjava.awt.TextArea;importjava.awt.TextField;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.EOFException;importjava.io.IOException;importjava.net.Socket;importjava.net.SocketException;importjava.net.UnknownHostException;public class ChatClient extendsFrame {
DataOutputStream dos= null;
Socket socket;
TextField inputChat= newTextField();
TextArea showChat= newTextArea();
DataInputStream dis= null;private static boolean isRun = false;
Thread tRecv= new Thread(newClientThread());public static voidmain(String[] args) {newChatClient().launchFrame();
}public voidlaunchFrame() {
setLocation(400, 300);
setSize(300, 300);
add(inputChat, BorderLayout.SOUTH);
add(showChat, BorderLayout.NORTH);
pack();
addWindowListener(newWindowAdapter() {
@Overridepublic voidwindowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
inputChat.addActionListener(newTextFieldListener());
setVisible(true);
connectToServer();
tRecv.start();
}private voidconnectToServer() {try{
socket= new Socket("127.0.0.1", 8888);
dos= newDataOutputStream(socket.getOutputStream());
dis= newDataInputStream(socket.getInputStream());
isRun= true;
}catch(UnknownHostException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}public voiddisconnect() {try{
dos.close();
dis.close();
socket.close();
}catch(IOException e) {
e.printStackTrace();
}//关闭各种流之前必须先关闭接受线程
}private class ClientThread implementsRunnable{
@Overridepublic voidrun() {try{while(isRun){
String str=dis.readUTF();
System.out.println(str);
showChat.setText(showChat.getText()+ str +'\n');
}
}catch(SocketException e) {
System.out.println("bye");
}catch(EOFException e) {
}catch(IOException e) {
e.printStackTrace();
}
}
}private class TextFieldListener implementsActionListener {
@Overridepublic voidactionPerformed(ActionEvent e) {
String s=inputChat.getText().trim();//showChat.setText(s);
inputChat.setText("");try{
dos.writeUTF(s);
dos.flush();//dos.close();
} catch(IOException e1) {
e1.printStackTrace();
}
}
}
}