Chinaunix首页 | 论坛 | 博客
  • 博客访问: 14374
  • 博文数量: 11
  • 博客积分: 480
  • 博客等级: 下士
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-30 08:42
文章分类

全部博文(11)

文章存档

2011年(1)

2008年(10)

我的朋友
最近访客

分类: Java

2008-11-28 17:48:21

ChatClient.java
 
package Chat;
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();
 Thread tRecv = new Thread(new RecvThread());
 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 arg0) {
    disconnect();
    System.exit(0);
   }
  });
  tfTxt.addActionListener(new TFListener());
  setVisible(true);
  connect();
  tRecv.start();
 }
 public void connect() {
  try {
   s = new Socket("127.0.0.1", 8888);
   dos = new DataOutputStream(s.getOutputStream());
   dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
   bConnected = true;
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 public void disconnect() {
  try {
   dos.close();
   dis.close();
   s.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  /*
  try {
   bConnected = false;
   tRecv.join();
  } catch(InterruptedException e) {
   e.printStackTrace();
  } finally {
   try {
    dos.close();
    dis.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 {
//System.out.println(s);
    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 (SocketException e) {
    System.out.println("閫
阅读(757) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~