⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 liaotiaoxitong.txt

📁 需在Jbuilder9.0环境下运行
💻 TXT
字号:
服务器端源代码(ChatServer.java)如下:
import java.net.*;
import java.io.*;
import java.util.*;
/**
 * <p>Title: Java Applet实现网络聊天室</p>
 * <p>Description: Java Applet是通过浏览器面向用户的Java小应用程序</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: cumt</p>
 * @author yanglinsen
 * @version 1.0
 */
public class ChatServer {
/*
* m_threads是一个Vector静态变量,它维护所有Server方的
* ServerThread实例,通过该变量能向所有连入Internet
* 的Applet广播信息
*/
//Chat Server的主方法入口。
//该方法监听Chat Applet的请求,并为新连接的
//Applet创建一个服务线程
  public static void main(String args[])
  {
        ServerSocket socket=null;
        Vector m_threads=new Vector();
        System.out.println("服务器已启动,正在等待客户的请求...");
        try
        {
            //设置Server监听端口号为8000, 这个数字必须
            //和程序ChatClient中的port参数一致。
            socket=new ServerSocket(8000);
        }
        catch(Exception e)
        {
            System.out.println("服务接口建立失败!");
            return;
        }
        try
        {
            int nid=0;
            while(true)
            {
                //监听是否有新Chat Applet连接到Server,
                //线程运行到该语句会封锁,直到有新的连接产生。
                Socket s=socket.accept();
                //创建一个新的ServerThread.
                ServerThread  st=new  ServerThread(s,m_threads);
                //为该线程设置一个ID号。
                st.setID(nid++);
                //将该线程加入到m_threads Vector中。
                m_threads.addElement(st);
                //启动服务线程。
                new Thread(st). start();
                //通知所有Chat Applet有一个新的网友加入。
                for(int i=0;i<m_threads.size();i++)
                {
                    ServerThread st1=(ServerThread)m_threads.elementAt(i);
                    st1.write("<服务器>欢迎 "+st.getID()+"号朋友进入聊天室!");
                }
                System.out.println("接受"+st.getID()+"号客户请求");
                System.out.println("继续等待其他客户的请求...\n");
            }
        }
        catch(Exception e)
        {
            System.out.println("服务器已关闭...");
        }

    }
}
/*
* 监听线程,监听对应的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("等待进程正在运行");
            try
            {
                while(true)
                {
                    //监听对应的Applet是否传来消息
                    //程序陷入到m_in.readUTF()中,直到有信息传来才返回。
                    String s=m_in.readUTF();
                    if (s==null)
                      break;
                    //如果Chat Applet传来的信息为"leave",
                    //则通知所有其他的的Chat Applet自己退出了。
                    if  (s.trim().equals ("leave"))
                      for (int i=0;i<m_threads.size();i++)
                        {
                          ServerThread st=(ServerThread)m_threads.elementAt(i);
                          st.write("*各位朋友, "+getID()+"号朋友离开聊天室"+"!*");
                        }
                    else
                    //向所有Chat Applet广播该信息。
                    for(int i=0;i<m_threads.size();i++)
                    {
                        ServerThread st=(ServerThread)m_threads.elementAt(i);
                        st.write("<"+getID()+"朋友说>"+s);
                    }
                }
            }
            catch(Exception e)
            {  e.printStackTrace();
            }
            //从m_threads Vector中删除该线程,表示该线程已经离开聊天室。
            m_threads.removeElement(this);
            try
            { m_socket.close();
            }
            catch (Exception e){}
        }
        //将msg送回对应的Applet
        public void write (String msg)
        {
            synchronized(m_out)
            {
                try
                {
                    m_out.writeUTF(msg);
                }
                catch(IOException e){}
            }
        }
        public int getID()  //获得该线程的ID.
        {
            return m_nid;
        }
        public void setID(int nid)  // //设置线程的ID.
        {
            m_nid=nid;
        }
}

客户端源代码(ChatClientApplet.java)如下:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import com.borland.jbcl.layout.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

/**
 * <p>Title: Java Applet实现网络聊天室</p>
 * <p>Description: Java Applet是通过浏览器面向用户的Java小应用程序</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: cumt</p>
 * @author yanglinsen
 * @version 1.0
 */

public class ChatClientApplet extends Applet implements Runnable {
  private boolean isStandalone = false;
  JLabel jLabel1 = new JLabel();
  JTextField jTextField1 = new JTextField();
  JLabel jLabel2 = new JLabel();
  JButton jButton1 = new JButton();
  DataInputStream  m_in;   //消息输入流
  DataOutputStream  m_out; //消息输出流
  JScrollPane jScrollPane1 = new JScrollPane();
  JTextArea jTextArea1 = new JTextArea();
  JLabel jLabel3 = new JLabel();
  //Get a parameter value
  public String getParameter(String key, String def) {
    return isStandalone ? System.getProperty(key, def) :
      (getParameter(key) != null ? getParameter(key) : def);
  }

  //Construct the applet
  public ChatClientApplet() {
  }
  //Initialize the applet
  public void init() {
    m_in=null;
    m_out=null;
    try{
      URL  url=getCodeBase();  //获取applet 的URL 值。
      //获取服务器IP地址
      InetAddress  inetaddr=InetAddress.getByName(url.getHost());
      Socket  m_socket;
      //屏幕显示服务器IP地址、通讯协议
      System.out.println("服务器:"+inetaddr+" "+url.getHost()+" "+url.getProtocol());
      m_socket=new Socket(inetaddr,8000); //创建与服务器IP地址连接的套接口
      //在套接口上建立输入流
      m_in=new  DataInputStream(m_socket.getInputStream());
      //在套接口上建立输出流
      m_out=new DataOutputStream(m_socket.getOutputStream());
    }
    catch (Exception e)
    {
      System.out.println("Error:"+e);
    }
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  //Component initialization
  private void jbInit() throws Exception {
    jLabel1.setFont(new java.awt.Font("DialogInput", 1, 20));
    jLabel1.setForeground(Color.red);
    jLabel1.setToolTipText("作者:杨林森  Email:yanglinsen@126.com");
    jLabel1.setText("一对多聊天程序Java Applet客户端");
    jLabel1.setBounds(new Rectangle(81, 22, 358, 38));
    this.setBackground(UIManager.getColor("ComboBox.selectionBackground"));
    this.setLayout(null);
    jLabel2.setFont(new java.awt.Font("Dialog", 1, 16));
    jLabel2.setForeground(Color.blue);
    jLabel2.setText("输入发送消息:");
    jLabel2.setBounds(new Rectangle(35, 78, 124, 37));
    jButton1.setBackground(UIManager.getColor("OptionPane.questionDialog.titlePane.background"));
    jButton1.setBounds(new Rectangle(413, 77, 70, 39));
    jButton1.setFont(new java.awt.Font("Dialog", 1, 16));
    jButton1.setForeground(Color.blue);
    jButton1.setToolTipText("点击发送按钮即可发送文本框中输入的消息");
    jButton1.setText("发送");
    jButton1.addActionListener(new ChatClientApplet_jButton1_actionAdapter(this));
    jTextField1.setBackground(new Color(182, 231, 223));
    jTextField1.setFont(new java.awt.Font("Dialog", 0, 17));
    jTextField1.setToolTipText("此文本框用来输入发送的消息");
    jTextField1.setBounds(new Rectangle(153, 80, 248, 35));
    jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.getViewport().setBackground(UIManager.getColor("MenuItem.acceleratorForeground"));
    jScrollPane1.setBounds(new Rectangle(54, 130, 410, 231));
    jTextArea1.setBackground(UIManager.getColor("Desktop.background"));
    jTextArea1.setFont(new java.awt.Font("Dialog", 0, 18));
    jTextArea1.setForeground(Color.black);
    jLabel3.setFont(new java.awt.Font("Dialog", 0, 16));
    jLabel3.setForeground(Color.blue);
    jLabel3.setText("如想离开聊天室,可在发送框中输入字符串leave并发送");
    jLabel3.setBounds(new Rectangle(62, 367, 394, 24));
    this.add(jLabel1, null);
    this.add(jLabel2, null);
    this.add(jTextField1, null);
    this.add(jButton1, null);
    this.add(jScrollPane1, null);
    this.add(jLabel3, null);
    jScrollPane1.getViewport().add(jTextArea1, null);
    //启动监听线程
    new Thread(this).start();
  }
  //Get Applet information
  public String getAppletInfo() {
    return "Applet Information";
  }
  //Get parameter info
  public String[][] getParameterInfo() {
    return null;
  }
  public void run()
    {
        try
        {
            while(true)
            {
             //监听服务者发来的消息,线程将阻塞在该语句中,直到消息到来。
                String s=m_in.readUTF();  //读一个UTF格式字符串。
                if(s!=null)
                //将消息显示在信息显示窗口中。
                jTextArea1.append(s+"\n");
            }
        }
            catch(Exception e)
            {
                jTextArea1.append("Network problem or Sever down.\n");
                jTextArea1.setVisible(false);
            }
        }
        public void stop()
        {
           try
           {
              m_out.writeUTF("leave");
              //如想离开聊天室,可在发送框中输入字符串leave
           }
           catch(IOException e){}
        }

    void jButton1_actionPerformed(ActionEvent e){
      String b = jTextField1.getText();
      jTextField1.setText("");
      //将用户输入的消息发送给 Chat Server
      try{
        m_out.writeUTF(b); //向服务者发送一UTF格式字符串。
      }
      catch(IOException g){}
    }
}

class ChatClientApplet_jButton1_actionAdapter implements java.awt.event.ActionListener {
  ChatClientApplet adaptee;

  ChatClientApplet_jButton1_actionAdapter(ChatClientApplet adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -