免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 2900 | 回复: 19
打印 上一主题 下一主题

有谁用JAVA写过聊天室? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-06-07 09:30 |只看该作者 |倒序浏览
请问,有谁用JAVA写过聊天室?如果有朋友真正做过,请赐教
如果有连接或者原代码介绍更好,谢谢

论坛徽章:
0
2 [报告]
发表于 2006-06-07 10:40 |只看该作者
用socket写过。

就很简单的实现。
两种功能,广播和单人聊天。

哈哈。

论坛徽章:
0
3 [报告]
发表于 2006-06-07 11:12 |只看该作者
写过跟QQ类似的聊天程序!(只能点对点聊天,无法群聊!功能非长不完善!)

论坛徽章:
0
4 [报告]
发表于 2006-06-07 18:04 |只看该作者
楼上的两位兄弟能给我提供原代码吗?
谢谢

论坛徽章:
0
5 [报告]
发表于 2006-06-07 18:52 |只看该作者
一年前写的。幸好找到了。

客户端:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;

public class Client extends JFrame implements

ItemListener,ActionListener
{
JButton jb,jb2,jb3;
JTextField jtf1,jtf2;
JTextArea jta;
JLabel jl;
JComboBox jbox;
String strbox[]={"所有人  "};
DataInputStream dis;
DataOutputStream dos;
Socket socket;
JScrollPane jScrollPane1 = new JScrollPane();
clientThread th;
String StrPerson=null;
String myName=null;
Client()
    {Container con=getContentPane();
     con.setLayout(new FlowLayout());     
     jb=new JButton("发言";
     jb.setEnabled(false);
     jb2=new JButton("登陆";
     jb3=new JButton("下线";
     jtf1=new JTextField(1;
     jtf2=new JTextField(12);
     
     jta=new JTextArea(15,25);
     jta.setAutoscrolls(true);
     
     jl=new JLabel("    发送给:";
     jbox=new JComboBox(strbox);
     //jbox.setSize(120,30);
     jta.setWrapStyleWord(true);
     jScrollPane1.getViewport().add(jta, null);
     jta.setEditable(false);
     con.add(jScrollPane1);
     con.add(jtf1);
     //jtf1.setVisible(false);
     //jb.setVisible(false);
     con.add(jb);
     con.add(jl);
     con.add(jbox);
     con.add(jtf2);
     con.add(jb2);
     con.add(jb3);
     
     jbox.addItemListener(this);
     jb.addActionListener(this);
     jb2.addActionListener(this);
     jb3.addActionListener(this);
     try
       {socket=new Socket("localhost",4331);
        dis=new DataInputStream(socket.getInputStream());
        dos=new DataOutputStream(socket.getOutputStream());
        th=new clientThread(socket,this);
        th.start();
       }
     catch(IOException ee){}
    }
public void itemStateChanged(ItemEvent e)
    {if(e.getItemSelectable()==jbox)           
       {if(jbox.getSelectedIndex()==0)
          StrPerson=null;
        else
                 StrPerson=jbox.getSelectedItem().toString();         
        }   
    }
public void actionPerformed(ActionEvent e)
    {
     if(e.getSource()==jb)
       {String kk=null;      
               String ss=jtf1.getText();
        if(ss!=null)
           {if(StrPerson==null)
              kk="MSG:"+ss;
            else
              kk="ONE"+StrPerson+":"+ss;
                   try
              {dos.writeUTF(kk);}
            catch(IOException e1){System.out.println("eee :";  }      

     
           }
       }
     if(e.getSource()==jb2)
       {        
               myName=jtf2.getText();
        if((myName!=null)&&(myName.trim()!="")
           {
            jb.setEnabled(true);
                   try
              {dos.writeUTF("LOGIN:"+myName);}
            catch(IOException e1){System.out.println("eee :";  }      

     
           }
       }
     
    }
public static void main(String args[])
    {Client c=new Client();
     c.setBounds(100,100,300,420);
     c.setResizable(false);
     c.setVisible(true);     
    }
}

class clientThread extends Thread
{DataInputStream in;
Socket client;
Client temp;
clientThread(Socket s,Client c)
   {client=s;
    temp=c;
    try
    {in=new DataInputStream(client.getInputStream());
     
    }
   catch (IOException e) {}
   }
public void run()
   {
           String s=null;
    try{
       while(true)
         {
          s=in.readUTF();
          if(!s.startsWith("NAMELIST:")
            temp.jta.append(s+"\n";
          else
           {StringTokenizer token=new StringTokenizer(s.substring

(9),"#";            
            while(token.hasMoreTokens())
             {
              String sss=token.nextToken();            
              boolean b=true;
              for(int y=0;y<(temp.jbox.getItemCount());y++)
                {String ch=temp.jbox.getItemAt(y).toString();
                 if(ch.trim().equals(sss.trim())||(sss.equals

(temp.myName)))            
                   {b=false;}
                }
              if(b)
                temp.jbox.addItem(sss);            
              }            
            }         
             }
            }
      catch(IOException e1){}
   }
}

服务器端:

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

public class Server implements Runnable
{public static final int PORT=4331;
protected ServerSocket listen;
static Vector connections;
String nameList="";
Thread connect;
public Server()
{try{listen=new ServerSocket(PORT);}
  catch(IOException e){System.err.println("erro:"+e);System.exit(1);}
  connections=new Vector(10);connect=new Thread(this);
  connect.start();
  }
public void run()
{try
  {while(true)
    {Socket client=listen.accept();
     firstthread f=new firstthread(this,client);
     f.setPriority(Thread.MIN_PRIORITY);
     f.start();
     connections.addElement(f);
     
     }
   }
catch (IOException e)
   {System.err.println("Erro:"+e);
    System.exit(1);
   }
}
public static void main(String[] args)
{new Server();}

public void broadcast(String msg)
   {int i; firstthread you;
    for(i=0;i<connections.size();i++)
      {you=(firstthread)connections.elementAt(i);
       System.out.println("you  :"+you.toString());
       try
         {you.out.writeUTF(msg);}
       catch (IOException e){}
       }
    }
public void sendmsg(String msg,String person)
   {int i; firstthread you;
    for(i=0;i<connections.size();i++)
      {you=(firstthread)connections.elementAt(i);
       if(you.name.equals(person))     
       try
         {you.out.writeUTF(msg);}
       catch (IOException e){}
       }
    }
}
class firstthread extends Thread
{protected Socket client;
String line,name;
int k=0;
protected DataOutputStream firstout,out;
protected Server server;
protected DataInputStream in;
firstthread d;
public firstthread(Server server,Socket client)
  {this.server=server;this.client=client;
   try
    {in=new DataInputStream(client.getInputStream());
     out=new DataOutputStream(client.getOutputStream());
     firstout=new DataOutputStream(client.getOutputStream());
    }
   catch (IOException e) {}
  }
public void run()
{try
   {for (int i=0;i<server.connections.size() ;i++ )
     {firstthread c=(firstthread)(server.connections.elementAt(i));
      if (c.name!=null)
        {try
          {firstout.writeUTF(c.name);}
         catch (IOException e){}
        }
      }
   }
catch (ArrayIndexOutOfBoundsException e){}
catch(NullPointerException e){}
try
  {while (true)
    {line=in.readUTF();
     try
      {d=(firstthread)server.connections.elementAt(server.connections.indexOf(this));}
     catch(Exception ee){}  
     if(line.startsWith("MSG:"))
       {if(d.name==null)
          {try
             {d.out.writeUTF("!!你没有登陆!请先登陆!!");}
           catch (IOException e){}
          }
        else
          {server.broadcast(d.name+" 说: "+line.substring(4));}
               }
     else if(line.startsWith("LOGIN:"))      
       {d.name=line.substring(6);
        server.broadcast("欢迎"+line.substring(6)+"上线");
        server.nameList=server.nameList+line.substring(6)+"#";
        server.broadcast("NAMELIST:"+server.nameList);
       }
     else if(line.startsWith("ONE"))
       {int nn=line.indexOf(":",1);
               server.sendmsg(d.name+" 说: "+line.substring(nn),line.substring(3,nn));
       }
     
     
     }
   }
catch (IOException e)
   {server.connections.removeElement(this);}
catch(NullPointerException e) { server.connections.removeElement(this);}
}
}

论坛徽章:
0
6 [报告]
发表于 2006-06-07 18:54 |只看该作者
这样贴出来的代码有其它符号。
直接上传文件又不行。

论坛徽章:
0
7 [报告]
发表于 2006-06-08 00:42 |只看该作者
xiexie

论坛徽章:
0
8 [报告]
发表于 2006-06-08 08:34 |只看该作者
贴代码的时候,请选择左边的禁用Smilies就好了。

论坛徽章:
0
9 [报告]
发表于 2006-06-08 11:56 |只看该作者
我想通过浏览器访问页面的时候聊天,也就是说把聊天室不要写成桌面程序,实行“瘦”客户端
策略。当客户端打开浏览器访问页面的时候,页面将呈现一个聊天界面给用户,程序完全集中在
服务器端,那,我该怎么办?

论坛徽章:
0
10 [报告]
发表于 2006-06-08 14:36 |只看该作者
哦。
那把发言内容放到application里行不.
不过这样的话,要不断刷新页面才能看到最新信息。
哈哈。
我也是菜鸟。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP