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

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值