您的位置:首页 > 编程语言 > Java开发

java聊天系统雏形........版本完善中,参考尚学堂第一个项目250行代码

2008-11-05 22:14 459 查看
贴代码

server端代码:

 

import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
 
 ServerSocket ss = null;
 boolean start = false;
 List<Client> clients = new ArrayList<Client>();

 public static void main(String[] args) {
  //创建一个对象并调用启动方法静态方法中不能创建内部类....
  new ChatServer().start();
 }
 
 public void start(){
  
  try {
   ss = new ServerSocket(8885);
  }catch (BindException e) {
   System.out.println("端口使用中....");
   System.out.println("请关掉相关程序并重新运行服务器!");
   System.exit(0);
  }catch(IOException e){
   System.out.print("服务器启动失败,请联系管理员!");
   System.out.print("如下信息被打印");   
   e.printStackTrace();
   System.exit(0);
   }
  start = true; 
  System.out.println("a ServerSocket newed!");
  try{
   while(start){
    //取得客户端的
    Socket s = ss.accept();    
    Client c = new Client(s);
    System.out.println("one Client accepted!");   
    clients.add(c);
    new Thread(c).start();
   }
  }catch (IOException e){
    e.printStackTrace();
  } finally {
   try {
    if(ss !=null) ss.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   
  }
 }
 
 
 class Client implements Runnable{
  
  private Socket s = null;
  private DataInputStream dis = null;
  private DataOutputStream dos = null;
  boolean bconnect = false;
  
  Client(Socket s){
   this.s = s;
   try {
    dis = new DataInputStream(s.getInputStream());
    dos = new DataOutputStream(s.getOutputStream());
    bconnect = true;
   } catch (IOException e) {
    e.printStackTrace();
   }  
   
  }
  
  public void run() {
   
   try {
    while(bconnect){
     String str = dis.readUTF();
     System.out.println(str);
     for(int i=0;i<clients.size();i++){
       Client c = clients.get(i);
       if(!this.equals(c))
        c.send(str);
     }
    }
   } catch (EOFException e) {
    System.out.println("The client is closed!");
    
   }catch (IOException e){
    e.printStackTrace();
   }
   
   finally{
    try {
     if(dis != null) dis.close();
     if(dos !=null)dos.close();
     if(s != null)s.close();
    } catch (IOException e1) {
     e1.printStackTrace();
    }
    clients.remove(this);
   }
  }
  
  public void send(String str){
   try {
    dos.writeUTF(str);
   } catch (IOException e) {
    System.out.println("东东要退出了");
  }

 }
}

 

 

 

 

 

下面是client端代码

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import java.io.*;

public class ChatClient extends Frame {
 
 Socket s = null;//创建一个Socket 供大家使用
 TextField tfText = new TextField();
 TextArea ttText = new TextArea();
 DataOutputStream dos;
 DataInputStream dis;
 private boolean bconnect = false;
 
 public static void main(String[] args) {
  new ChatClient().launchFrame(); 

 }
 
 public void launchFrame() {
  //设置Frame的一些相关属性
  this.setLocation(400, 300);
  this.setSize(300, 300);
  
  //Frame类的默认布局管理器是BorderLayout
  //使用add方法把文本框和文本区域加入Frame中
  //BorderLayout会自动进行布局管理
  //注意要调用pack()方法打包使得结构紧凑
  this.add(tfText, BorderLayout.SOUTH);
  this.add(ttText, BorderLayout.NORTH);
  
  //自动打包,使得Frame中的布局紧凑,
  //调用的是Window类中的的方法,Frame类是Window的子类
  this.pack();
  
  //加入该Frame对象的监听器,创建一个匿名类,这个类没有名字
  this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent arg0) {
    super.windowClosing(arg0);
    disconnect();
    System.exit(0);    
   }
   });
  
  //设置TextField类对象tf的监听器,创建的对象为内部类创建的对象
  tfText.addActionListener(new TfActionListener());
  //Frame设置为现实,传true
  this.setVisible(true);
  this.connect();
 }
 
 //创建一个内部类来供Frame来使用,
 //这个类重写了actionPerformed方法,从而实现了ActionListener接口,
 public class TfActionListener implements ActionListener{

  public void actionPerformed(ActionEvent arg0) {
   //拿出tfText中的值,显示到ttText中,并设置tfText为空
   String str = tfText.getText().trim();//trim方法为去掉开头和结尾的空格,是String中的方法
   ttText.setText(ttText.getText()+str+"/n");
   tfText.setText("");  
   
   //拿到Socket,取出outputstream
   //Socket对象中getOutputStream()方法中返回的流就是outPutStream
   //在outPutStream中在包一层 DataOutputStream(传入OutPutStream()); 
   //创建这个管道后,向管道里写入utf字符str   
   try {
    dos.writeUTF(str);
    dos.flush();
   } catch (IOException e) {
    e.printStackTrace();
     }
   
  }

   
 }
  

 //拿到端口,并把一个数据流兑到端口上
 public void connect(){
  try {
   s =new Socket("127.0.0.1",8885);
   dos = new DataOutputStream(s.getOutputStream());
   dis = new DataInputStream(s.getInputStream());
   bconnect = true;
System.out.println("good connect!");
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
     
  WriteThread sw = new WriteThread(dis);   
  new Thread(sw).start();
 }

 //关闭管道和端口,处理抛出的异常
 public void disconnect(){
  
  bconnect = false;
  try {
   dos.close();
   s.close();
  } catch (IOException e) {
   e.printStackTrace();
   }
  
 }

 class  WriteThread implements Runnable{
  
  DataInputStream dis = null;
  
  WriteThread (DataInputStream dis){
   this.dis = dis;
  }

  public void run() { 
   try {
    while(bconnect){
     String str = dis.readUTF();
     ttText.setText(ttText.getText() + str + '/n');
    }

   } catch (IOException e) {
    
    System.out.println("程序已经关闭");
   }  
  }
  
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐