|
客户端代码:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
public static void main(String[] args) {
new ChatClient().launchFrame();
}
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
public void launchFrame() {
this.setLocation(400, 300);
setSize(300,300);
add(tfTxt,BorderLayout.SOUTH);
add(taContent,BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
this.setVisible(true);
connect();
}
public void connect() {
try {
s = new Socket("172.16.42.30",8888);
dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
taContent.setText(str);
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} |
|