ClinentChat.java

来源:互联网 发布:rar mac中文版 编辑:程序博客网 时间:2024/04/29 19:48

package chatroom;
import java.applet.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.Hashtable;
//实现runnable接口,实现多继承。要实现Runnable的run方法,不能直接创建runnable类来运行,必须借助thread类
public class ClinentChat extends Applet implements Runnable {
 //变量申明
 Socket socket=null;
 DataInputStream in=null;
 DataOutputStream out=null;
 InputNameTextField submit=null;
 ChatArea chatSpace=null;
 Hashtable listTable;
 Label  tishi=null;
 Panel north,center;
 Thread thread;//用来运行runnable对象
 //初始化工作
 public void init(){
  setSize(800,400);
  int width=getSize().width;
  int height=getSize().height;
  listTable =new Hashtable();
  setLayout(new BorderLayout());
  submit =new InputNameTextField(listTable);
  int h=submit.getSize().height;
  chatSpace=new ChatArea("",listTable,width,height-(h+5));
  chatSpace.setVisible(false);
  tishi=new Label("正在连接到服务器,请稍等...",Label.CENTER);
  tishi.setForeground(Color.red);
  north=new Panel(new FlowLayout(FlowLayout.LEFT));
  center=new Panel();
  north.add(submit);
  north.add(tishi);
  center.add(chatSpace);
  add(north,BorderLayout.NORTH);
  add(center,BorderLayout.CENTER);
  validate();//??
 }
 //
 public void start(){
  //清除以前的套接字连接
  if(socket!=null&&in!=null&&out!=null){
   try{
    socket.close();
   }catch(Exception e){
   }
  }
  //与服务器套接字建立连接
  try{
   socket =new Socket(this.getCodeBase().getHost(),6666);//??
   in=new DataInputStream(socket.getInputStream());
   out=new DataOutputStream(socket.getOutputStream());
   }catch(IOException e){
    tishi.setText("连接失败");
   }
  //如果套接字连接成功,提示用户登录
  if(socket!=null){
   InetAddress address=socket.getInetAddress();
   tishi.setText("连接"+address+"成功");
   submit.setSocketConnection(socket,in,out);
   north.validate();
  }
  //为该用户启动一个新线程
  if(thread==null){
   thread=new Thread(this);
   thread.start();
  } 
 }
 //
 public void stop(){
  try{
   socket.close();
   thread=null;
  }catch(IOException e){
   this.showStatus(e.toString());
   
  }
 }
    //
 public void run(){
  while(thread!=null){
   if(submit.getCanChat()==true){
    chatSpace.setVisible(true);
    chatSpace.setName(submit.getName());
    chatSpace.setSocketConnection(socket,in,out);
    tishi.setText("祝聊天愉快!");
    center.validate();
    break;
   }
   try{
    Thread.sleep(100);
   }catch(Exception e){}
  }
 }
}