//聊天室的客戶端   
  import   java.applet.*;   
  import   java.awt.*;   
  import   java.io.*;   
  import   java.net.*;   
  import   java.awt.event.*;       
  public   class   ChatClient   extends   Applet{   
        protected   boolean   loggedIn;//登入狀態   
        protected   Frame   cp;//聊天室框架   
        protected   static   int   PORTNUM=7777;   //預設埠號7777   
        protected   int   port;//實際埠號   
        protected   Socket   sock;   
        protected   BufferedReader   is;//用於從sock讀取數據的BufferedReader   
        protected   PrintWriter   pw;//用於向sock寫入數據的PrintWriter   
        protected   TextField   tf;//用於輸入的TextField   
        protected   TextArea   ta;//用於顯示對話的TextArea   
        protected   Button   lib;//登入按鈕   
        protected   Button   lob;//登出的按鈕   
        final   static   String   TITLE   ="Chatroom   applet>>>>>>>>>>>>>>>>>>>>>>>>";   
        protected   String   paintMessage;//發表的消息   
        public   ChatParameter   Chat;               
        public   void   init(){   
        paintMessage="正在生成聊天窗口";   
        repaint();   
        cp=new   Frame(TITLE);   
        cp.setLayout(new   BorderLayout());   
        String   portNum=getParameter("port");//呢個參數勿太明   
        port=PORTNUM;   
        if   (portNum!=null)     //書上是portNum==null,十分有問題   
              port=Integer.parseInt(portNum);                   
        //CGI             
        ta=new   TextArea(14,80);   
        ta.setEditable(false);//read   only   attribute   
        ta.setFont(new   Font("Monospaced",Font.PLAIN,11));   
        cp.add(BorderLayout.NORTH,ta);             
        Panel   p=new   Panel();   
        Button   b;             
        //for   login   button   
        p.add(lib=new   Button("Login"));   
        lib.setEnabled(true);   
        lib.requestFocus();   
        lib.addActionListener(new   ActionListener()   {   
        public   void   actionPerformed(ActionEvent   e){   
        login();   
        lib.setEnabled(false);   
        lob.setEnabled(true);   
        tf.requestFocus();//將鍵盤輸入鎖定再右邊的文本框中   
        }   
        });             
        //for   logout   button   
        p.add(lob=new   Button   ("Logout"));   
        lob.setEnabled(false);   
        lob.addActionListener(new   ActionListener(){   
        public   void   actionPerformed(ActionEvent   e){   
        logout();   
        lib.setEnabled(true);   
        lob.setEnabled(false);   
        lib.requestFocus();   
        }   
        });   
        p.add(new   Label ("輸入消息:"));   
        tf=new   TextField(40);   
        tf.addActionListener(new   ActionListener(){   
        public   void   actionPerformed(ActionEvent   e){   
        if(loggedIn){   
        //pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野來?   
        int   j=tf.getText().indexOf(":");   
        if(j>0)   pw.println(Chat.CMD_MESG+tf.getText());           
        else   
        pw.println(Chat.CMD_BCAST+tf.getText());   
        tf.setText("");//勿使用flush()?   
        }   
        }     
        });             
        p.add(tf);   
        cp.add(BorderLayout.SOUTH,p);               
        cp.addWindowListener(new   WindowAdapter(){   
        public   void   windowClosing(WindowEvent   e){   
        //如果執行了setVisible或者dispose,關閉窗口   
        ChatClient.this.cp.setVisible(false);   
        ChatClient.this.cp.dispose();   
        logout();   
        }   
        });             
        cp.pack();//勿明白有咩用?   
        //將Frame   cp放在中間   
        Dimension   us=cp.getSize(),   
          them=Toolkit.getDefaultToolkit().getScreenSize();   
          int   newX=(them.width-us.width)/2;   
          int   newY=(them.height-us.height)/2;   
          cp.setLocation(newX,newY);   
          cp.setVisible(true);   
          paintMessage="Window   should   now   be   visible";   
          repaint();               
            }          
      //登錄聊天室   
      public   void   login(){   
      if(loggedIn)       return;           
      try{   
            sock=new   Socket(getCodeBase().getHost(),port);   
            is=new   BufferedReader(new   InputStreamReader(sock.getInputStream()));   
            pw=new   PrintWriter(sock.getOutputStream(),true);   
            }catch(IOException   e){   
            showStatus("Can't   get   socket:   "+e);   
            cp.add(new   Label("Can't   get   socket:   "+e));   
            return;}                 
        //構造並且啟動讀入器,從伺服器讀取數據,輸出到文本框中   
        //這里,長成一個線程來避免鎖住資源(lockups)       
        new   Thread   (new   Runnable(){   
        public   void   run(){   
        String   line;   
        try{   
            while(loggedIn   &&((line=is.readLine())!=null))   
                ta.appendText(line+"\n");   
                }catch(IOException   e){   
                showStatus("我的天啊,掉線了也!!!!");   
                return;   
                }   
                                                        }   
                                      }).start();          
//假定登錄(其實只是列印相關信息,並沒有真正登錄)  
//   pw.println(Chat.CMD_LOGIN+"AppletUser");   
                      pw.println(Chat.CMD_LOGIN+"AppletUser");   
                        loggedIn   =true;               
              
          }                                 
      //模仿退出的代碼   
      public   void   logout(){   
      if(!loggedIn)   
            return;                 
            loggedIn=false;   
            try{   
                  if(sock!=null)   
                        sock.close();             
            }catch(IOException   ign){   
            //   異常處理哦   
            }           
    }     
        //沒有設置stop的方法,即使從瀏覽器跳到另外一個網頁的時候   
        //聊天程序還可以繼續運行             
        public   void   paint(Graphics   g){   
        Dimension   d=getSize();   
        int   h=d.height;   
        int   w=d.width;   
        g.fillRect(0,0,w,2);   
        g.setColor(Color.black);   
        g.drawString(paintMessage,10,(h/2)-5);   
        }             
  } 
聊天室伺服器端   
  import   java.net.*;   
  import   java.io.*;   
  import   java.util.*;   
    
  public   class   ChatServer{   
        //聊天室管理員ID   
        protected   final   static   String   CHATMASTER_ID="ChatMaster";   
        //系統信息的分隔符   
        protected   final   static   String   SEP=":   ";   
        //伺服器的Socket   
        protected   ServerSocket     servSock;   
        //當前客戶端列表   
        protected   ArrayList   clients;   
        //調試標記   
        protected   boolean   DEBUG=false;   
        public   ChatParameter   Chat;   
          
        //主方法構造一個ChatServer,沒有返回值   
        public   static   void   main(String[]   argv){   
        System.out.println("Chat   server0.1   starting>>>>>>>>>>>>>>>>");   
        ChatServer   w=new   ChatServer();   
        w.runServer();   
        System.out.println("***ERROR***   Chat   server0.1   quitting");   
            
            }   
//構造和運行一個聊天服務   
        ChatServer(){   
        Chat=new   ChatParameter();   
        clients=new   ArrayList();   
        try{   
              servSock=new   ServerSocket(7777);//實有問題拉,不過可能是他自己定義既一個class.   
              System.out.println("Chat   Server0.1   listening   on   port:"+7777);   
              }catch(Exception   e){   
              log("IO   Exception   in   ChatServer.<init>");   
              System.exit(0);   
                }   
                            }   
                              
          public   void   runServer(){   
          try{   
                while(true){   
                Socket   us=servSock.accept();   
                String   hostName=us.getInetAddress().getHostName();   
                System.out.println("Accpeted   from   "+hostName);   
                //一個處理的線程   
                ChatHandler   cl=new   ChatHandler(us,hostName);   
                synchronized(clients){   
                clients.add(cl);   
                cl.start();   
                if(clients.size()==1)   
                      cl.send(CHATMASTER_ID,"Welcome!You   are   the   first   one   here");   
                  else{   
                      cl.send(CHATMASTER_ID,"Welcome!You   are   the   latest   of"+   
                            clients.size()+"   users.");   
                            }       
                  }   
                  }   
          }catch(Exception   e){   
          log("IO   Exception   in   runServer:"+e);   
          System.exit(0);   
          }   
          }   
protected   void   log(String   s){   
          System.out.println(s);   
          }   
//處理會話的內部的類   
            protected   class   ChatHandler   extends   Thread   {   
            //客戶端scoket   
            protected   Socket   clientSock;   
            //讀取socket的BufferedReader   
            protected   BufferedReader   is   ;   
            //在socket   上發送信息行的PrintWriter   
            protected   PrintWriter   pw;   
            //客戶端出主機   
            protected   String   clientIP;   
            //句柄   
            protected   String   login;   
              
            public   ChatHandler   (Socket   sock,String   clnt)throws   IOException   {   
            clientSock=sock;   
            clientIP=clnt;   
            is=new   BufferedReader(   
                      new   InputStreamReader(sock.getInputStream()));   
              pw=new   PrintWriter   (sock.getOutputStream(),true);       
              
            }   
              
                  //每一個ChatHandler是一個線程,下面的是他的run()方法   
                  //用於處理會話   
                  public   void   run(){   
                  String   line;   
                    
                  try{   
                        while((line=is.readLine())!=null){   
                        char   c=line.charAt(0);//我頂你老母啊   ,果只Chat.CMD咩xx冇定義   撲啊///!!!   
                        line=line.substring(1);   
                        switch(c){   
                        //case   Chat.CMD_LOGIN:   
                        case   'l':   
                                  if(!Chat.isValidLoginName(line)){   
                                  send(CHATMASTER_ID,"LOGIN"+line+"invalid");   
                                  log("LOGIN   INVALID   from:"+clientIP);   
                                  continue;   
                                  }   
                                    
                                  login=line;   
                                  broadcast(CHATMASTER_ID,login+"   joins   us,for   a   total   of"+   
                                                        clients.size()+"   users");   
                                  break;   
                                    
                        //   case   Chat.CMD_MESG:   
                        case   'm':   
                                if(login==null){   
                                send(CHATMASTER_ID,"please   login   first");   
                                continue;   
                                }   
                                  
                                int   where   =line.indexOf(Chat.SEPARATOR);   
                                String   recip=line.substring(0,where);   
                                String   mesg=line.substring   (where+1);   
                                log("MESG:   "+login+"--->"+recip+":   "+mesg);   
                                ChatHandler   cl=lookup(recip);   
                                if(cl==null)   
                                      psend(CHATMASTER_ID,recip+"not   logged   in.");   
                                else   
                                      cl.psend(login,mesg);   
                                        
                                break;   
//case   Chat.CMD_QUIT:   
                            case   'q':   
                                broadcast(CHATMASTER_ID,"Goodbye   to   "+login+"@"+clientIP);   
                                close();   
                                return;//ChatHandler結束   
//   case   Chat.CMD_BCAST:   
                          case   'b':   
                                    if(login!=null)   
                                          broadcast(login,line);   
                                    else   
                                          log("B<L   FROM"+clientIP);   
                                      break;   
                                        
                              default:   
                                      log("Unknow   cmd"+c+"from"+login+"@"+clientIP);   
                                                }   
                                      }   
                                            }catch(IOException   e){   
                                            log("IO   Exception   :"+e);   
                                            }finally{   
                                                  //sock   結束,我們完成了   
                                                  //還不能發送再見的消息   
                                                  //得有簡單的基於命令的協議才行   
                                                  System.out.println(login+SEP+"All   Done");   
                                                  synchronized(clients){   
                                                  clients.remove(this);   
                                                  if(clients.size()==0){   
                                                  System.out.println(CHATMASTER_ID+SEP+   
                                                                    "I'm   so   lonely   I   could   cry>>>>>");   
                                                            }else   if(clients.size()==1){   
                                                            ChatHandler   last=(ChatHandler)clients.get(0);   
                                                            last.send(CHATMASTER_ID,"Hey,you   are   talking   to   yourself   again");   
                                                            }   
                                                            else{   
                                                            broadcast(CHATMASTER_ID,"There   are   now"+clients.size()+"   users");   
                                                            }   
                                                  }   
                                              }   
                                          }                 
            protected   void   close(){   
            if(clientSock==null){   
            log("close   when   not   open");   
            return;   
            }   
            try{   
                clientSock.close();   
                clientSock=null;   
                }catch(IOException   e){   
                log("Failure   ring   close   to   "+clientIP);   
                }   
            }               
            //發送一條消息給用戶   
            public   void   send(String   sender,String   mesg){   
            pw.println(sender+SEP+"*>"+mesg);   
            }                 
            //發送私有的消息   
            protected   void   psend(String   sender   ,String   msg){   
            send("<*"+sender+"*>",msg);   
            }   
            //發送一條消息給所有的用戶   
            public   void   broadcast   (String   sender,String   mesg){   
            System.out.println("Broadcasting"+sender+SEP+mesg);   
            for(int   i=0;i<clients.size();i++){   
            ChatHandler   sib=(ChatHandler)clients.get(i);   
            if(DEBUG)   
                  System.out.println("Sending   to"+sib);   
            sib.send(sender,mesg);   
                                    }                   
                              if(DEBUG)   System.out.println("Done   broadcast");   
                      }                           
              protected   ChatHandler   lookup(String   nick){   
              synchronized(clients){   
              for(int   i=0;i<clients.size();i++){   
              ChatHandler   cl=(ChatHandler)clients.get(i);   
              if(cl.login.equals(nick))   
              return   cl;   
              }   
                                                }   
                                    return   null;               
                      }                              
              //將ChatHandler對象轉換成一個字元串   
              public   String   toString(){   
              return   "ChatHandler["+login+"]";   
              }                 
            }                           
  } 
public   class   ChatParameter   {   
  public   static   final   char   CMD_BCAST='b';   
  public   static   final   char   CMD_LOGIN='l';   
  public   static   final   char   CMD_MESG='m';   
  public   static   final   char   CMD_QUIT='q';   
  public   static   final   char   SEPARATOR=':';//?????   
  public   static   final   int   PORTNUM=7777;   
  public   boolean   isValidLoginName(String   line){   
  if   (line.equals("CHATMASTER_ID"))   
        return   false;   
    return   true;       
  }   
  public   void   main(String[]   argv){   
  }     
  }   
以上代碼由於界面限制的原因 可能有點兒亂
把它整個復制出去 重新整理修改一下就行了
『貳』 求用Java編寫的聊天室界面
jsp的
<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>歡樂聊天室</title>
</head>
<body>
<%--首先取出用戶提交的代號名稱,保存在變數chatid中--%>
<%
  String chatid = new String();
  chatid = request.getParameter("inputid");
%>
<%--使用變數flag來標記用戶輸入是否合法,如果合法,則flag為true --%>
<%
  boolean flag;
  flag = true;
  if(chatid == null){
    chatid = "";
  }
  if(chatid.length() == 0){
    flag = false;
  }
%>
<%--比較用戶所輸入的id和目前聊天室中存在的所有id --%>
<%
  for(int i=1; i<=6 && flag; i++){
    String itemp = new String();
    itemp = itemp.valueOf(i);
    int num;
    String numtemp = new String();
    String temp = new String();
    temp = "room" + itemp + "usernum";
    numtemp = (String)application.getAttribute(temp);
    if(numtemp == null){
      numtemp = "0";
      application.setAttribute(temp ,numtemp);
    }
    num = Integer.parseInt(numtemp);
    for(int j=1; j<=num && flag; j++){
      String jtemp = new String();
      jtemp = jtemp.valueOf(j);
%>
<%--從application對象中取出第i個聊天室中第j個用戶的id,temp變數保存的是application對象用於保存第i個聊天室中第j個用戶的id相應的變數名 --%>
<%
  temp = "room" + itemp + "user" + jtemp;
  String usertemp = new String();
  usertemp = (String)application.getAttribute(temp);
  if(usertemp.equalsIgnoreCase(chatid)){
    flag = false;
  }
    }
  }
int nnn[] = new int[6];
if(flag){
  String temproom = new String();
  temproom = (String)session.getValue("chatroom");
  if(temproom == null){
    session.putValue("chatid",chatid);
    
  }
  for(int i=1; i<=6; i++) {
    String itemp = new String();
    itemp = itemp.valueOf(i);
    int num;
    String numtemp = new String();
    String temp = new String();
    temp = "room" + itemp + "usernum";
    numtemp = (String)application.getAttribute(temp);
    if(numtemp == null){
      numtemp = "0";
    }
    num = Integer.parseInt(numtemp);
    nnn[i-1] = num;
  }
}
%>
<p align="center"><b><font face="隸書" size="6" color="#FF00FF">歡樂聊天室</font></b></p>
<%
  if(flag){
%>
<p align="center"><font color="red"><%=chatid %></font>您好,請選擇感興趣的聊天室!</p>
<center><table border="1" width="370">
  <tr>
    <td width="50%"><a href="JSPchat.jsp?chatroom=1">今天我們相識(<%=nnn[0]%>)</a></td>
    <td width="50%"><a href="JSPchat.jsp?chatroom=2">校園的那條小路(<%=nnn[1]%>)</a></td>
  </tr>
  <tr>
    <td width="50%"><a href="JSPchat.jsp?chatroom=3">職場淘金(<%=nnn[2]%>)</a></td>
    <td width="50%"><a href="JSPchat.jsp?chatroom=4">網路技術交流(<%=nnn[3]%>)</a></td>
  </tr>
  <tr>
    <td width="50%"><a href="JSPchat.jsp?chatroom=5">世界體育大看台(<%=nnn[4]%>)</a></td>
    <td width="50%"><a href="JSPchat.jsp?chatroom=6">新聞背後的故事(<%=nnn[5]%>)</a></td>
  </tr>
</table><center>
<%
  }else {
%>
<center><p>id不能為空,或者此id已經被使用,請重新選擇!</p><center>
<p><center><a href="login.html">返回</a><center></p>
<%
  }
%>
</body>
</html>
『叄』 java實現聊天室是怎麼做到的
Java 實現聊天室可以分為以下幾個步驟:
建立伺服器端
首先需要建立一個伺服器端,負責接收客戶端的連接請求並處理客戶端發送過來的消息。
建立客戶端
然後需要建立冊陸客戶端,客戶端通過正姿畢網路連接到伺服器端,並向伺服器端發送消息。
實現通信協議
為了實現聊天室功能,需要定義一個通信協議,規定客戶端和伺服器端之間的通信格式,例如消息的頭部和內容等。
實現多線程處理
聊天室通常會有多個用戶同時在線,因此需要使用多線程舉芹來處理多個客戶端的連接請求和消息傳遞。
實現GUI界面(可選)
為了方便用戶使用,可以實現一個GUI界面,讓用戶可以方便地發送和接收消息。
以下是一個簡單的 Java 聊天室的代碼示例:
java
Copy code
// 伺服器端代碼
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ServerThread(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ServerThread implements Runnable {
    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;
    public ServerThread(Socket socket) {
        this.socket = socket;
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run() {
        try {
            String msg;
            while ((msg = reader.readLine()) != null) {
                // 處理客戶端發送過來的消息
                System.out.println("接收到消息:" + msg);
                // 將消息發送給所有客戶端
                for (Socket s : ServerThreadList.getList()) {
                    if (s != socket) {
                        PrintWriter w = new PrintWriter(s.getOutputStream());
                        w.println(msg);
                        w.flush();
                    }
                }
            }
            // 關閉連接
            socket.close();
            ServerThreadList.removeThread(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ServerThreadList {
    private static List
 list = new ArrayList<>();
    public static void addThread(ServerThread thread) {
        list.add(thread);
    }
    public static void removeThread(ServerThread thread) {
        list.remove(thread);
    }
    public static List
 getList() {
        return list;
    }
}
// 客戶端代碼
public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 8888);
            new Thread(new ClientThread(socket)).start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            while (true) {
                String msg = reader.readLine();
                writer.println(msg);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ClientThread implements Runnable {
    private Socket socket;
    private BufferedReader reader;
    public ClientThread(Socket socket) {
        this.socket = socket;
        try {
            reader
『肆』 為java聊天室代碼加詳細注釋,並說明設計思路。好的加100分。
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//引入包。
public class ChatClient {
 public static void main(String[] args) {
  ChatClient cc = new ChatClient();
  cc.receive();
 }
 JTextField jtf; // 文本條
 JTextArea jta; //文本域。
 Socket s; //客戶端
 PrintWriter out; //輸出流
 BufferedReader in; //輸入流
 public ChatClient() {
  JFrame frame = new JFrame("ChatClient");//窗口
  frame.setSize(400, 300); //大小
  jta = new JTextArea(); //文本域
  jta.setEditable(false); //不可編輯
  jtf = new JTextField();//文件條
  jtf.addActionListener(new ActionListener() { //添加監聽。
   public void actionPerformed(ActionEvent arg0) {
    send(); //調用send()方法
   }
  });
  frame.getContentPane().add(new JScrollPane(jta)); //添加滾動條
  frame.getContentPane().add(jtf, "South"); //添加文本條
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口。
  frame.setVisible(true); //可顯示的。
  try {
   s = new Socket("127.0.0.1", 9000); //連接服務端 socket("主機名",埠號);
   in = new BufferedReader(new InputStreamReader(s.getInputStream())); //建立輸入流
   out = new PrintWriter(s.getOutputStream());//輸出流
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void receive() { //接受服務端發來別的客戶端的信息。
  while (true) {
   try {
    String text = in.readLine(); //讀一行
    this.jta.append(text + "\n"); //jta 添加上讀入的。
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
   }
  }
 }
 public void send() { //發送消息
  String text = this.jtf.getText(); //得到你輸入的消息
  this.jtf.setText(""); //在文本域中顯示你輸入的消息。
  out.println(text); //列印出。
  out.flush(); //清空
 }
}
Server端
import java.net.*;
import java.io.*;
import java.util.*;//引入包
public class ChatServer {
 public static void main(String[] args) throws Exception {
  ServerSocket ss = new ServerSocket(9000); //建立服務端,埠號為9000
  List list = new ArrayList(); //創建個List集合。
  while (true) { 
   Socket s = ss.accept(); //等待客戶端的請求。
   list.add(s); //把每一個client都add到集合中去。
   Thread t = new ServerThread(s, list); //線程。
   t.start(); //啟動。
  }
 }
}
class ServerThread extends Thread {
 Socket s; 
 List list;
 BufferedReader in;
 PrintWriter out;
 public ServerThread(Socket s, List list) { //構造。傳入socket和list。
  this.s = s;
  this.list = list;
  try {
   in = new BufferedReader(new InputStreamReader(s.getInputStream())); //輸入流
   out = new PrintWriter(s.getOutputStream()); //輸出流
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void run() { //必須實現其run()方法。
  while (true) {
   try {
    String str = in.readLine(); //得到client端的message。
    if (str == null) //如果沒有消息就返回。
     return;
    Iterator it = list.iterator(); //遍歷list。
    while (it.hasNext()) { //如果list有下一個
     Socket socket = (Socket) (it.next()); //因為list中都是存的socket
     PrintWriter o = new PrintWriter(socket.getOutputStream()); //輸出流
     o.println(str); //輸出
     o.flush(); //清空
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    // e.printStackTrace();
    return;
   }
  }
 }
}
『伍』 急需一個用java 語言寫的聊天程序
客戶端: 
package chatroom; 
import java.awt.*; 
import java.awt.event.*; 
import java.net.*; 
import java.io.*; 
import javax.swing.*; 
public class client extends JFrame implements ActionListener,Runnable{ 
JPanel conn,text,send; 
JLabel name,sendto; 
JComboBox list; 
JButton con,snd,clear; 
JTextArea talk; 
JTextField who,say; 
JScrollPane jsp; 
Socket client; 
InputStream is; 
OutputStream os; 
PrintStream ps; 
BufferedReader br; 
String receive,yousay; 
Thread th; 
DataInputStream dis; 
Double tof; 
client() 
{ 
super("聊天室客戶端"); 
this.setSize(800,600); 
this.setResizable(false); 
conn=new JPanel(); 
text=new JPanel(); 
send=new JPanel(); 
this.getContentPane().add(conn); 
conn.setBounds(0, 0, this.getWidth(),50); 
name=new JLabel("姓名:"); 
who=new JTextField(); 
con=new JButton("連接"); 
conn.setLayout(null); 
conn.add(name); 
name.setBounds(30, 10, 50, 25); 
conn.add(who); 
who.setBounds(80, 10, 150, 25); 
conn.add(con); 
con.setBounds(250,10, 60, 25); 
this.getContentPane().add(text); 
text.setBounds(0,50,this.getWidth(),450); 
text.setLayout(new BorderLayout()); 
jsp=new JScrollPane(); 
talk=new JTextArea(); 
jsp.getViewport().setView(talk); 
text.add(jsp,"Center"); 
talk.setLineWrap(true); 
this.getContentPane().add(send); 
send.setLayout(null); 
send.setBounds(0, 480, this.getWidth(), 150); 
sendto=new JLabel("發送到:"); 
snd=new JButton("發送"); 
list=new JComboBox(); 
say=new JTextField(); 
clear=new JButton("清空"); 
send.add(sendto); 
sendto.setBounds(30, 525, 50, 25); 
send.add(list); 
list.setBounds(100, 525, 75, 25); 
send.add(say); 
say.setEditable(true); 
say.setBounds(200, 525, 300, 25); 
send.add(snd); 
snd.setBounds(520, 525, 100, 25); 
send.add(clear); 
clear.setBounds(650, 525, 100, 25); 
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
this.setVisible(true); 
con.addActionListener(this); 
snd.addActionListener(this); 
} 
public void actionPerformed(ActionEvent ae) { 
if (ae.getActionCommand().equals("連接")) 
{ 
try 
{ 
client=new Socket(InetAddress.getLocalHost(),55555); 
talk.append("連接成功...\n"); 
con.setText("斷開"); 
is=client.getInputStream(); 
os=client.getOutputStream(); 
th=new Thread(this); 
String id=who.getText(); 
byte b[]=id.getBytes(); 
DataOutputStream dos=new DataOutputStream(os); 
int len=b.length; 
dos.writeInt(len); 
dos.write(b); 
th.start(); 
}catch(Exception e){talk.append("連接失敗\n"+e.toString()+"0000");} 
} 
else if(ae.getSource()==snd) 
{ 
if(list.getSelectedItem().toString()=="所有人") 
{ 
yousay="@open"+say.getText(); 
byte b[]=yousay.getBytes(); 
DataOutputStream dos=new DataOutputStream(os); 
try{ 
int len=b.length; 
dos.writeInt(len); 
dos.write(b); 
}catch(Exception e) 
{ 
System.out.print(e.toString()+"1111"); 
} 
} 
else 
{ 
yousay="@whisper"+say.getText(); 
byte b[]=yousay.getBytes(); 
byte w[]=list.getSelectedItem().toString().getBytes(); 
DataOutputStream dos=new DataOutputStream(os); 
try{ 
int len=b.length; 
int wlen=w.length; 
dos.writeInt(len); //內容 
dos.write(b); 
dos.writeInt(wlen); //發送對象 
dos.write(w); 
}catch(Exception e) 
{ 
System.out.print(e.toString()+"AAAA"); 
} 
} 
} 
else if(ae.getActionCommand().equals("斷開")) 
{ 
try 
{ 
client.close(); 
talk.append("連接已斷開\n"); 
con.setText("連接"); 
}catch(Exception e){System.out.println(e.toString()+"2222");} 
} 
} 
public void run() 
{ 
while(true) 
{ 
try 
{ 
dis=new DataInputStream(is); 
tof=dis.readDouble(); 
if(tof==1.1) 
{ 
dis=new DataInputStream(is); 
int number; 
list.removeAllItems(); 
list.addItem("所有人"); 
number=dis.readInt(); 
for(int i=0;i<number;i++) 
{ 
int len=dis.readInt(); 
byte b[]=new byte[len]; 
dis.read(b); 
String name=new String(b); 
list.addItem(name); 
} 
} 
else if(tof==2.2) 
{ 
try 
{ 
dis=new DataInputStream(is); 
int len=dis.readInt(); 
byte b[]=new byte[len]; 
dis.read(b); 
receive=new String(b); 
talk.append(receive+"\n"); 
}catch(Exception e){JOptionPane.showMessageDialog(this, "連接已斷開","消息",JOptionPane.INFORMATION_MESSAGE);break;} 
} 
}catch(Exception e){JOptionPane.showMessageDialog(this, "連接已斷開","消息",JOptionPane.INFORMATION_MESSAGE);break;} 
} 
} 
public static void main(String[] args) { 
client cl=new client(); 
} 
} 
服務端: 
package chatroom; 
import java.awt.*; 
import javax.swing.*; 
import java.net.*; 
import java.util.Vector; 
import java.io.*; 
public class server extends JFrame implements Runnable{ 
JPanel jp1; 
JTextArea jta; 
JScrollPane jsp; 
Socket socket=null; 
ServerSocket server; 
InputStream is; 
OutputStream os; 
static int i=0,login; 
int no; 
static String s=""; 
Thread sr; 
Thread th[]=new Thread[20]; 
static Vector ol=new Vector(); 
static public byte w[]=null; 
static String from=""; //人名 
static String to=""; 
static String fromtext=""; //內容 
static String totext=""; 
server() 
{ 
super("聊天室服務端"); 
this.getContentPane().setLayout(new GridLayout(1,1)); 
this.setSize(400,300); 
jp1=new JPanel(); 
jta=new JTextArea(); 
jsp=new JScrollPane(); 
this.getContentPane().add(jp1); 
jp1.setLayout(new GridLayout(1,1)); 
jsp.getViewport().setView(jta); 
jp1.add(jsp); 
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
setVisible(true); 
} 
public static void main(String[] args) { 
server sr=new server(); 
sr.sr=new Thread(sr); 
sr.sr.start(); 
sendtoall sta=new sendtoall(); 
returnfrom rf=new returnfrom(sr); 
returnto rt=new returnto(sr); 
sta.start(); 
rf.start(); 
rt.start(); 
} 
public void run() 
{ 
try 
{ 
server=new ServerSocket(55555); 
while(true) 
{ 
socket=server.accept(); 
is=socket.getInputStream(); 
DataInputStream dis=new DataInputStream(is); 
int len=dis.readInt(); 
byte b[]=new byte[len]; 
dis.read(b); 
String id=new String(b); 
record v=new record(id,socket); 
ol.addElement(v); 
for (int i=0;i<ol.size();i++) 
{ 
if (ol.elementAt(i).equals(v)) 
{ 
no=i; 
} 
} 
login=1; 
s=id+"已來到聊天室!"; 
th[no]=new Thread(new receive(this,no)); 
th[no].start(); 
} 
}catch(Exception e){System.out.println(e.toString()+"aaaa");} 
} 
} 
class receive implements Runnable 
{ 
InputStream is; 
OutputStream os; 
server sr; 
Socket sk; 
int i; 
String name; 
String ip; 
receive(server sr,int i) 
{ 
this.sr=sr; 
this.i=i; 
sk=((record)sr.ol.elementAt(i)).ip; 
name=((record)sr.ol.elementAt(i)).name; 
ip=((record)sr.ol.elementAt(i)).ip.getInetAddress().toString(); 
} 
public void run() 
{ 
while(true) 
{ 
try 
{ 
is=sk.getInputStream(); 
DataInputStream dis=new DataInputStream(is); 
int len=dis.readInt(); 
byte b[]=new byte[len]; 
dis.read(b); 
String abc=new String(b); 
sr.jta.append(abc); 
if(abc.substring(0,5).equals("@open")) 
{ 
server.s=name+"["+ip.substring(1, ip.length())+"]"+"說:"+abc.substring(5,abc.length()); 
sr.jta.append(server.s+"\n"); 
} 
else if(abc.substring(0,8).equals("@whisper")) 
{ 
int wlen=dis.readInt(); 
sr.w=new byte[wlen]; 
dis.read(sr.w); 
server.to=new String(sr.w); 
server.from=((record)sr.ol.elementAt(i)).name; 
String ip=((record)sr.ol.elementAt(i)).ip.getInetAddress().toString(); 
// server.s=server.from+"對"+server.to+"["+ip.substring(1, ip.length())+"]"+"悄悄地說:"+abc.substring(8,abc.length()); 
server.fromtext="你對"+server.to+"["+ip.substring(1, ip.length())+"]"+"悄悄地說:"+abc.substring(8,abc.length()); 
server.totext=server.from+"["+ip.substring(1, ip.length())+"]"+"對你悄悄地說:"+abc.substring(8,abc.length()); 
sr.jta.append(server.s+"\n"); 
} 
}catch(Exception e) 
{ 
try 
{ 
DataOutputStream dos=new DataOutputStream(os); 
server.ol.removeElementAt(i); 
server.s=name+"已離開聊天室."; 
server.login=1; 
break; 
}catch(Exception f){} 
} 
} 
} 
} 
class sendtoall extends Thread 
{ 
int len,number; 
byte b[]; 
server sr; 
Socket st; 
OutputStream os; 
DataOutputStream dos; 
public void run() 
{ 
while(true) 
{ 
try 
{ 
if(server.login==1) 
{ 
number=0; 
number=server.ol.size(); 
dos=new DataOutputStream(os); 
for(int i=0;i<server.ol.size();i++) 
{ 
st=((record)sr.ol.elementAt(i)).ip; 
os=st.getOutputStream(); 
dos=new DataOutputStream(os); 
dos.writeDouble(1.1); 
dos.writeInt(number); 
for (int j=0;j<number;j++) 
{ 
String name=((record)sr.ol.elementAt(j)).name; 
byte b[]=name.getBytes(); 
int len=b.length; 
dos.writeInt(len); 
dos.write(b); 
} 
} 
server.login=0; 
} 
else if(!server.s.equals("")&&sr.ol.size()>0) 
{ 
b=server.s.getBytes(); //String類型中 漢字佔一個位元組,但是byte類型中,漢字占兩個位元組 
len=b.length; 
//len=server.s.length(); 
//b=new byte[len]; 
//b=server.s.getBytes(); 
for(int i=0;i<server.ol.size();i++) 
{ 
st=((record)sr.ol.elementAt(i)).ip; 
os=st.getOutputStream(); 
DataOutputStream dos=new DataOutputStream(os); 
dos.writeDouble(2.2); 
dos.writeInt(len); 
dos.write(b); 
} 
server.s=""; 
} 
}catch(Exception e){System.out.println(e.toString()+"sdasd");} 
} 
} 
} 
class returnfrom extends Thread 
{ 
int len,wlen; 
byte b[]; 
byte w[]; 
server sr; 
Socket st; 
OutputStream os; 
DataOutputStream dos; 
//String from="",to=""; 
returnfrom(server sr) 
{ 
this.sr=sr; 
} 
public void run() 
{ 
while(true) 
{ 
if(!server.fromtext.equals("")) 
{ 
b=server.fromtext.getBytes(); 
len=b.length; 
sr.jta.append(sr.fromtext); 
try 
{ 
for(int i=0;i<server.ol.size();i++) 
{ 
if(((record)sr.ol.elementAt(i)).name.equals(server.from)) 
{ 
st=((record)sr.ol.elementAt(i)).ip; 
os=st.getOutputStream(); 
DataOutputStream dos=new DataOutputStream(os); 
dos.writeDouble(2.2); 
dos.writeInt(len); 
dos.write(b); 
} 
} 
}catch(Exception e){System.out.println(e.toString()+"wwww");} 
server.fromtext=""; 
server.from=""; 
} 
} 
} 
} 
class returnto extends Thread 
{ 
int len,wlen; 
byte b[]; 
byte w[]; 
server sr; 
Socket st; 
OutputStream os; 
DataOutputStream dos; 
//String from="",to=""; 
returnto (server sr) 
{ 
this.sr=sr; 
} 
public void run() 
{ 
while(true) 
{ 
if(!server.totext.equals("")) 
{ 
w=server.totext.getBytes(); 
wlen=w.length; 
try 
{ 
for(int i=0;i<server.ol.size();i++) 
{ 
if(((record)sr.ol.elementAt(i)).name.equals(server.to)) 
{ 
st=((record)sr.ol.elementAt(i)).ip; 
os=st.getOutputStream(); 
DataOutputStream dos=new DataOutputStream(os); 
dos.writeDouble(2.2); 
dos.writeInt(wlen); 
dos.write(w); 
} 
} 
}catch(Exception e){System.out.println(e.toString()+"wwww");} 
server.totext=""; 
server.to=""; 
} 
} 
} 
} 
class record 
{ 
String name; 
Socket ip; 
record(String id,Socket socket) 
{ 
name=id; 
ip=socket; 
} 
} 
以前學習java時寫的,是個在線聊天室只有群聊,私聊,上下線提示,搞不好裡面還有錯誤- -其他功能自己看著加吧,你要的功能實在是很好很強大.
『陸』 我做java的簡易聊天室,已經可以群聊和私聊,如何把創建房間加進去,且只能同一個房間里才能群聊和私聊
我說下思路:
1、客戶端創建房間時給每個房間分配惟一的一個房間ID,房間是公開的,每個連接的客戶端都可以看到,房間屬性,比如密碼,比如黑名單,房間保存在Server內存當中,如果你使用了集群,建議存儲到分布式緩存當中(Redis是最好的選擇,其次是memcached),當創建完成後,將房間信息發送給所有客戶端。新客戶端連接進來時,客戶端要主動從服務端拉取房間信息。建議採用服務端主動通知(房間增減,服務端主動通知給所有客戶端)和客戶端定時輪詢(客戶端起個定時任務,每隔一定時間主動向服務端拉取房間列表)的方式來保證房間列表的動態更新。
2、當客戶端選擇加入房間時,如果設置有加入條件,比如密碼,那就提示客戶端輸入,如果是其他條件就判斷加入客戶端是否符合這個條件。服務端保存房間同客戶端的關聯關系(可以設計成一對多,也就是一個客戶端只能在一個房間聊天,也可以設計成多對多,一個客戶端可以同時加入多個房間聊天,主要看設計),並將這個消息通知給這個房間所有的客戶端列表「歡迎***進入房間」(消息的發送者為系統,房間ID這個房間的ID,接收人無,表示是這個房間的公開消息,消息內容即:歡迎***進入房間。)
3、把聊天內容當成消息的話,那消息應該有這樣的屬性,發送人,房間ID(如果沒有房間ID就當成系統公告消息,在所有房間顯示),接收人(如果沒有指定接收人,則是公開消息,如果有接收人,就是私聊消息,只能在同一個房間私聊,那在發消息的時候要判斷下接收客戶端的是否在這個房間列表當中)。
4、再來說消息路由設置,當客戶端發送消息時,根據房間ID,找到這個這個房間內所有的客戶端列表,如果沒有指定接收人,那消息就推送給這個房間關聯的所有客戶端,如果指定有接收人,接收人不在這個房間,直接提示「***已經離開」,如果還在就把消息推送給這個指定的客戶端。
5、房間的管理:踢人,把這個客戶端從房間同客戶端關聯關系解除,並在房間顯示消息「***被踢出房間」等等