package com.chat;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.net.*;
import java.io.*;

public class ChatClient extends JFrame implements ActionListener{
  private JTextField txf;
  private JTextArea ta;
  private Socket ss=null;
  private DataOutputStream dos=null;//输出流
  private DataInputStream dis=null;
  private boolean connected=false;
  public static void main(String args[])
  {
    new ChatClient();
  }
    
  public ChatClient() {
    super();
    setBounds(100, 100, 412, 328);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    txf = new JTextField();
    getContentPane().add(txf, BorderLayout.SOUTH);
    txf.addActionListener(this);
    
    ta = new JTextArea();
    ta.setColumns(10);
    ta.setEditable(false);
    ta.setForeground(Color.RED);

    getContentPane().add(ta, BorderLayout.CENTER);
    this.connectServer();
    Thread t=new Thread(new ReceiveThread());
    t.start();
    this.setVisible(true);//窗口可见    
    /*this.addWindowListener(new WindowAdapter(){
      public void WindowClosing(WindowEvent e)
      {
        System.exit(0);
        disconnect();
      }
    });*/

    
  }
  public    void connectServer()
  {
    try {
      ss=new Socket("127.0.0.1",2222);
      dos=new DataOutputStream(ss.getOutputStream());
      dis=new DataInputStream(ss.getInputStream());
      connected=true;
    } catch (UnknownHostException e) {
      System.out.println("没有找到主机!");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }    
  }
  public void sendMessage(String sendStr) throws IOException
  {
    dos.writeUTF(sendStr);
    dos.flush();
  }

    
  private void disconnect()
  {
    try {
      dos.close();
      System.out.println("输出流已经关闭!");
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      ss.close();
      System.out.println("Socket已经关闭!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  class ReceiveThread implements Runnable
  {
    public void run()
    {
      try{
    
      while(connected)
      {
        String str = dis.readUTF();
        System.out.println(str);
        ta.setText(str);
      }
      }catch(IOException e){
        e.printStackTrace();
      }
    }
  }
  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource().equals(txf)&&!txf.getText().trim().equals(""))
    {
      String str=txf.getText();
      //ta.setText(str);
      if(!ta.getText().trim().equals(""))
      ta.append("\n");
      if(txf.getText().trim().equals("cls"))
      {
        ta.setText("");
        txf.setText("");
        return;
      }
      //发送消息
      try {
        this.sendMessage(str);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      ta.append(str);
      txf.setText("");
    }
  }
}



package com.chat;

import java.util.List;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.io.*;

public class ChatServer    
{
  List<Client> clientList=new ArrayList<Client>();
    
  public static void main(String args[])
  {
    new ChatServer().start();
  }    

  class Client implements Runnable
  {
    //成员变量
    private DataInputStream dis=null;
    private DataOutputStream dos=null;
    private boolean connected=false;
    private Socket s=null;
    //构造函数
    Client(Socket s)
    {    
      this.s=s;
    }
    //向指定用户发送消息
    public void sendMessage(String str)
    {
      for(int i=0;i<clientList.size();i++)
      {
        try {
          dos.writeUTF(str);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    
    //run方法
    public void run()    
    {
      connected=true;
      try {
        dis = new DataInputStream(s.getInputStream());//得到输入流
        dos = new DataOutputStream(s.getOutputStream());//得到输出流
        while(connected)
        {
          String str=dis.readUTF();
          System.out.println(str);    
          for(int i = 0;i<clientList.size(); i++ )
          {            
            clientList.get(i).sendMessage(str);//把消息发个客户端
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      finally
      {
        try{
        if(s!=null)
          s.close();
        if(dis!=null)
          dis.close();
        if(dos!=null)
          dos.close();
        }
        catch(IOException e)
        {
          System.out.println(e.toString());
        }
      }
    }
    
  }
  public void start()
  {    
    boolean started = false;
    ServerSocket ss=null;
    try {
      ss = new ServerSocket(2222);  //开启服务器
      started=true;//若开启成功则started=true;
      System.out.println("服务器已开启!");
      }
      catch(BindException e){
        System.out.println("端口使用中");
      }
      catch (IOException e2) {
      e2.printStackTrace();
      }
        
      while(started)//判断服务器是否开启
      {
        boolean connected = false;//判断客户端
        Socket s;
        try {
          s = ss.accept();//接受一个socket
          Client c=new Client(s);//构造一个客户端
          this.clientList.add(c);//加入列表
          Thread t=new Thread(c);
          t.start();
          System.out.println("一个客户端已经连接...");//提示
          } catch (IOException e)    
          {
            e.printStackTrace();

        
      }
    }
}
}