Java多個用戶端聊天程式實現程式

來源:互聯網
上載者:User
 代碼如下 複製代碼


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


public class HeartServer {
    
    /*
     * 成員變數閃亮登場
     */
    List<ClientThread> clients = new ArrayList<ClientThread>();
   
    /**
     * 這系入口啊,向這裡看齊...
     * @param args
     */
    public static void main(String[] args) {
        new HeartServer().start();
    }
   
    /**
     * 啟動伺服器中...
     *
     */
    public void start(){
        try {
            boolean iConnect = false;
            ServerSocket ss = new ServerSocket(1720);
            iConnect = true;
            while(iConnect){
System.out.println("綁定伺服器連接埠成功!");
                Socket s = ss.accept();
                ClientThread currentClient = new ClientThread(s);//建立線程引用
System.out.println("發現用戶端!");
                clients.add(currentClient);//把當前用戶端加入集合
                new Thread(currentClient).start();
System.out.println("用戶端進程已經啟動!");
            }
        } catch (IOException e) {
            System.out.println("IOException");
            e.printStackTrace();
        }
    }
   
    /**
     * 給每個用戶端留個家(用戶端的進程)
     *
     */
    class ClientThread implements Runnable {
        /*
         * 成員變數又來啦...
         */
        private Socket s;
        private DataInputStream dis;
        private DataOutputStream dos;
        private String str;
        private boolean iConnect = false;
       
        /**
         * 小構一下
         */
        ClientThread(Socket s){
            this.s = s;
            iConnect = true;
        }
       
        public void run(){
System.out.println("run方法啟動了!");
            try {
               
                while(iConnect){
System.out.println("RUN方法中的while迴圈啟動,正在等待用戶端的發送訊息...");
                    dis = new DataInputStream(s.getInputStream());
                    str = dis.readUTF();
System.out.println(str);
                    for(int i=0; i<clients.size(); i++){
System.out.println("轉寄訊息中..."+i);
                        ClientThread c = clients.get(i);
                        c.sendMsg(str);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
           
        }
       
        /**
         * 轉寄訊息,我做主...
         * 將送至伺服器的訊息發送給每個串連到的用戶端
         */
        public void sendMsg(String str){
            try {
System.out.println("建立輸出管道!");
                dos = new DataOutputStream(this.s.getOutputStream());
System.out.println("正在向用戶端寫訊息!");
                dos.writeUTF(str);
System.out.println("正在向用戶端寫訊息成功!");           
            } catch (IOException e) {
                e.printStackTrace();
            }
           
        }
       
    }
   
}


程式

 代碼如下 複製代碼

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

public class HeartClient extends Frame {

    /*
     *  成員方法出場...
     */
    private TextField tfText;
    private TextArea taContent;
    private Socket s;
    private DataOutputStream dos;
    private DataInputStream dis;
   
    /**
     * 注意,入口... ^^
     * @param args
     */
    public static void main(String[] args) {
        new HeartClient().launchFrame();
       
    }
   
    /**
     * Loading GU
     */
    public void launchFrame(){
        tfText = new TextField();
        taContent = new TextArea();
        this.setSize(300,300);
        this.setLocation(300,300);
        this.tfText.addActionListener(new TFListener());
        this.add(tfText,BorderLayout.SOUTH);
        this.add(taContent,BorderLayout.NORTH);
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }});
        this.pack();
        this.connect();
        this.setVisible(true);
    }

    /**
     * 我在努力地串連伺服器中...
     */
    public void connect() {
        try {
            s = new Socket("127.0.0.1",1720);
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            new Thread(new SendThread()).start();
//            dos.writeUTF("Hello,i find u!");
        } catch (UnknownHostException e) {
            System.out.println("UnknownHostException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IOException");
            e.printStackTrace();
        }finally{
            //關閉啥尼...
        }
       
    }

    /**
     * 額不會傻等著tfText(TextField tfText的監聽器類)
     */
    class TFListener implements ActionListener{
        private String str;
        @Override
        public void actionPerformed(ActionEvent e) {
            str = tfText.getText().trim();
            tfText.setText("");
            try {
                dos.writeUTF(str);
            } catch (IOException e1) {
                System.out.println("IOException");
                e1.printStackTrace();
            }
        }
       
    }
   
    /**
     * 用戶端接收訊息的線程呦...
     *
     */
    class SendThread implements Runnable{
        private String str;
        private boolean iConnect = false;
       
        public void run(){
            iConnect = true;
            recMsg();
           
        }
       
        /**
         * 訊息,看招,哪裡跑...(用戶端接收訊息的實現)
         * @throws IOException
         */
        public void recMsg() {
            try {
                while(iConnect){
                    str = dis.readUTF();
                    taContent.setText(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
           
        }
       
    }
   
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.