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

来源:互联网 发布:淘宝踏板摩托车骗局 编辑:程序博客网 时间:2024/05/22 04:35

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

}

原创粉丝点击