您的位置:首页 > 理论基础 > 计算机网络

模拟QQ聊天程序_客户端_网络编程

2011-05-11 17:53 585 查看
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient extends Frame { //创建客户端程序
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;

TextField tfTxt = new TextField(); //创建窗口各元素

TextArea taContent = new TextArea();

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

}

public void launchFrame() { //创建符合要求的聊天窗口
setLocation(400, 300);
this.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();

new Thread(new RecvThread()).start();
}

public void connect() {
try {
s = new Socket("127.0.0.1", 8888); //设置好服务器地址,端口
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
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 {

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();
}
}

}

private class RecvThread implements Runnable {

public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '/n'); //把接受到的数据显示出来
}
} catch (IOException e){
e.printStackTrace();
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: