java "群发"聊天demo

来源:互联网 发布:软件过程能力 编辑:程序博客网 时间:2024/05/31 06:22
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * chat server
 *
 * @author Sam
 *
 */
public class Server
{
    private List<Client> clients = new ArrayList<Client>();
    
    public static void main(String[] args)
    {
        Server server = new Server();
        server.lauchServer();
    }

    /**
     * to laucher a server
     */
    public void lauchServer()
    {
        ServerSocket server = null;
        try
        {
            server = new ServerSocket(8182);
            System.out.println("the server lauch successfull!");
        }
        catch (IOException e)
        {

        }

        while (true)
        {
            try
            {
                Socket socket = server.accept();
                Client client = new Client(socket);
                client.start();
                clients.add(client);
            }
            catch (Exception ex)
            {

            }
        }
    }

    private final class Client extends Thread
    {
        private Socket socket;
        private DataInputStream read = null;
        private DataOutputStream write = null;
        public Client(Socket socket)
        {
            this.socket = socket;
        }

        /**
         * to send the msg
         * @param read
         * @throws IOException
         */
        private void sendMSG(String msg)throws IOException
        {
            write.writeUTF(msg);
        }
        
        /**
         * retrun true if client has still connected the server, or false
         * @return
         */
        public boolean isConnectedServer()
        {
            return this.socket.isClosed()?false:true;
        }
        
        @Override
        public void run()
        {
            
            try
            {
                write = new DataOutputStream(socket.getOutputStream());
                while (true)
                {
                    read = new DataInputStream(socket.getInputStream());
                    String msg = read.readUTF();
                    for(Client client : clients)
                    {
                        if(client.isConnectedServer())
                        {
                            client.sendMSG(msg);
                        }
                    }
                    
                }
            }
            catch (IOException e)
            {
            }
            finally
            {
                if(null != socket)
                {
                        try
                        {
                            if(null != write)
                                write.close();
                            if(null != read)
                                read.close();
                            if(null !=socket)
                                socket.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
            }

        }
    }

}



---------------------------------------------------------------------------------------------------------------------------------------------------------------------------




import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * chat client
 * @author Sam
 *
 */
public class Client extends JFrame
{
    private JTextArea area = new JTextArea();//chat list
    private JTextField field = new JTextField();//send sms field
    private Socket socket;
    private DataOutputStream write;
    private DataInputStream read ;
    public Client()
    {
        this.setBounds(500, 200, 300, 300);
        this.setTitle("Client");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        area.setEnabled(false);
        area.setBackground(Color.red);
        this.add(BorderLayout.CENTER, area);
        field.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0)
            {
                //area.append("say:"+field.getText()+"\n");
                try
                {
                    write.writeUTF(field.getText());
                }
                catch (IOException e)
                {
                    System.out.println("you can not send the message, your client stream was closed!");
                }
                
                field.setText("");
                
            }
        });
        this.add(BorderLayout.SOUTH, field);
    }
    
    /**
     * to lauch the Client and connect the server
     */
    public void lauchClient()
    {
        this.setVisible(true);
        connect();
    }
    /**
     * to connect the server
     */
    public void connect()
    {
        try
        {
            System.out.println("client is connecting...!");
            socket = new Socket("127.0.0.1", 8182);
            System.out.println("client  connected!");
            write = new DataOutputStream(socket.getOutputStream());
            read = new DataInputStream(socket.getInputStream());
            while(true)
            {
                String receive = read.readUTF();
                area.append(receive+"\n");
            }
            
        }
        catch (Exception e)
        {
            System.out.println("error! client socket is closing...");
        }
        finally
        {
            if(null !=socket)
            {
                try
                {
                    write.close();
                    read.close();
                    socket.close();
                    System.out.println("client socket was closed!");
                }
                catch (IOException e)
                {
                    
                }
            }
        }
        
    }
    
    public static void main(String[] args)
    {
        Client client = new Client();
        client.lauchClient();
    }
}




0 0