java 聊天程式

來源:互聯網
上載者:User

標籤:

package cn.apr.chart;

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

public class ChatServer {
    /**
     * @param args
     *            m_threads是一個Vector靜態變數,維護所有Server方的ServerThread對象,
     *            通過該變數能向所有加入聊天室的聊天者ChatApplet廣播資訊,撤銷退出的聊天者。
     *            聊天服務者ChatServer的主方法。該方法監聽聊天者Chat Applet的請求, 並為新串連的聊天者建立一個服務線程。
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ServerSocket socket = null;
        Vector m_threads = new Vector();
        System.out.println("listen...");
        try {
            // 設定ServerSocket監聽連接埠號碼為5555,這個數字必須和程式聊天者ChatApplet中的port參數一致
            socket = new ServerSocket(5555);
        } catch (Exception e) {
            System.out.println("new ServerSocket() failed!");
            return;
        }
        try {
            int nid = 0;
            while (true) {
                // 監聽是否有新聊天者Chat Applet串連到聊天Server,
                // 線程運行到該語句會封鎖,直到有新的串連產生
                Socket s = socket.accept();
                System.out.println("accepted");
                // 建立一個新的ServerThread
                ServerThread st = new ServerThread(s, m_threads);
                // 為該線程設定一個ID號
                st.setID(nid++);
                // 將線程加入到m_threads Vector中
                m_threads.addElement(st);
                // 啟動服務線程
                new Thread(st).start();
                // 通知所有ChatApplet有一個新的網友加入
                for (int i = 0; i < m_threads.size(); i++) {
                    ServerThread st1 = (ServerThread) m_threads.elementAt(i);
                    st1.write("<#>welcome" + st.getID() + "to enter chatroom!");
                }
                System.out.println("Listen again...");
            }
        } catch (Exception e) {
            System.out.println("Server is down...");
        }
    }
}

// 監聽線程,監聽對應的Chat Applet是否有資訊傳來
class ServerThread implements Runnable {
    Vector m_threads;
    Socket m_socket = null;
    DataInputStream m_in = null;
    DataOutputStream m_out = null;
    int m_nid;

    // 初始化線程
    public ServerThread(Socket s, Vector threads) {
        m_socket = s;
        m_threads = threads;
        try {
            // 構造資料輸入、輸出資料流對象
            m_in = new DataInputStream(m_socket.getInputStream());
            m_out = new DataOutputStream(m_socket.getOutputStream());
        } catch (Exception e) {
        }
    }

    public void run() // 線程的執行體
    {
        System.out.println("thread is running");
        try {
            while (true) {
                // 監聽對應的ChatApplet是否傳來訊息
                // 線程封鎖在m_in.readUTF()中,直到有資訊傳來才返回
                String s = m_in.readUTF();
                if (s == null)
                    break;
                // 如果Chat Applet傳來的資訊為“leave”,則通知所有其他的ChatApplet自己推出了
                if (s.trim().equals("leave"))
                    for (int i = 0; i < m_threads.size(); i++) {
                        ServerThread st = (ServerThread) m_threads.elementAt(i);
                        st.write("***" + getID() + "leave..." + "***");
                    }
                else
                    // 向所有ChatApplet廣播該訊息
                    for (int i = 0; i < m_threads.size(); i++) {
                        ServerThread st = (ServerThread) m_threads.elementAt(i);
                        st.write("<" + getID() + ">" + s);
                    }
            } // while(true)
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 從m_threads Vector中刪除該線程,表示該線程已經離開聊天室
        m_threads.removeElement(this);
        System.out.println("remove element!");
        try {
            m_socket.close();
        } catch (Exception e) {
        }
    }

    // 將msg送回對應的Applet
    public void write(String msg) {
        synchronized (msg) {
            try {
                m_out.writeUTF(msg);
            } catch (IOException e) {
            }
        }
    }

    public int getID() // 獲得該線程的ID
    {
        return m_nid;
    }

    public void setID(int nid) // 設定線程的ID
    {
        m_nid = nid;
    }
}

//////////////

package cn.apr.chart;

import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;

//繼承Applet,實現Runnable
public class ChatApplet1 extends Applet implements Runnable {
    TextArea m_textarea; // 接受訊息顯示視窗
    TextField m_textfield; // 發送訊息輸入視窗
    DataInputStream m_in; // 訊息輸入資料流
    DataOutputStream m_out; // 訊息輸出資料流

    /**
     * @param args
     *  ChatApplet的初始化方法
     */
    public void init() {
        // 建立視窗
        setLayout(null);
        setSize(426, 266);
        m_textarea = new TextArea(10, 10);
        m_textfield = new TextField();
        m_in = null;
        m_out = null;
        // 初始化Appleton,並串連到聊天服務者
        try {
            // 擷取applet的URL,即通過伺服器位址
            URL url = getCodeBase();
            // 擷取伺服器IP地址
            InetAddress inetaddr = InetAddress.getByName(url.getHost());
            Socket m_socket;
            // 螢幕顯示伺服器IP地址、通訊協定
            System.out.println("Server:" + inetaddr + "" + url.getHost() + ""
                    + url.getProtocol());
            // 建立與伺服器IP地址串連的套介面,5555是聊天伺服器套介面連接埠
            m_socket = new Socket(inetaddr, 5555);
            // 在套介面上建立輸入資料流
            m_in = new DataInputStream(m_socket.getInputStream());
            // 在套介面上建立輸出資料流
            m_out = new DataOutputStream(m_socket.getOutputStream());
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
        setLayout(new BorderLayout());
        add("Center", m_textarea);
        add("South", m_textfield);
        m_textarea.setEditable(false);
        // 啟動監聽線程
        new Thread(this).start();
    }

    // 當聊天者在訊息輸入視窗鍵入斷行符號後,讀取字串,發送給聊天服務者。

    public boolean handleEvent(Event event) {
        String b = m_textfield.getText();
        if ((event.target == m_textfield) && (event.id == Event.ACTION_EVENT)) {
            m_textfield.setText("");
            // 將聊天者輸入的訊息發送給ChatServer
            try {
                m_out.writeUTF(b); // 向聊天服務者發送一個UFT格式字串
            } catch (IOException e) {
            }
            return true;
        } else
            return super.handleEvent(event);
    }

    // 聊天者監聽對應的服務線程,在讀取對應服務線程傳來的訊息,並顯示在通訊顯示視窗中

    public void run() {
        try {
            while (true) {
                // 聊天者監聽對應服務線程發來的訊息,它將封鎖在該語句中,直到訊息到來
                String s = m_in.readUTF(); // 讀一個UTF格式字串
                if (s != null)
                    // 將訊息顯示在資訊顯示視窗中
                    m_textarea.append(s + "\n");
            }
        } catch (Exception e) {
            m_textarea.append("Network problem or Server down.\n");
            m_textfield.setVisible(false);
        }
    }

    public void stop() {
        try {
            m_out.writeUTF("leave");
        } catch (IOException e) {
        }
    }

    public static void main(String[] args) {
        // TODO 自動產生方法存根
    }
}

java 聊天程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.