java聊天室程序源代码 java聊天程序设计代码-成都快上网建站

java聊天室程序源代码 java聊天程序设计代码

您有java聊天室代码吗?能发给我一份吗?578014735@qq.com 太感谢了

import java.util.*;

桓台网站建设公司创新互联建站,桓台网站设计制作,有大型网站制作公司丰富经验。已为桓台上千余家提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的桓台做网站的公司定做!

import java.io.*;

import java.net.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

/*=============表情面板================*/

class ImagePane extends JDialog implements ActionListener {

final int icon_max = 95;Icon _icon;int _face;

String[] face = new String[icon_max];

ImageIcon[]icon = new ImageIcon[icon_max];

JButton[]btn = new JButton[icon_max];

ImagePane(Frame f, String ipath){

super(f,"ImageIcon",true);

setBounds(100,100,300,300);

setLayout( new GridLayout(12,10) );

for(int i=0;iicon_max;i++){

face[i] =ipath + i + ".gif";

icon[i] = new ImageIcon(face[i]);

btn[i] = new JButton(icon[i]);

btn[i].addActionListener(this);add(btn[i]);

}

}

public void actionPerformed(ActionEvent e){

Object o = e.getSource();

for(int i=0;iicon_max;i++){

if(o==btn[i]){

_face = i; _icon = icon[i]; setVisible(false); return;

}

}

}

public Icon getIcon(int i){

return icon[i];

}

public Icon getIcon(){

return _icon;

}

public int getFace(){

return _face;

}

}

/*================主面板=================*/

class Pane extends JFrame implements ActionListener , Runnable {

JTextPane text1 = new JTextPane();

JTextPane text2 = new JTextPane();

JScrollPane sc1= new JScrollPane(text1,22,32);

JScrollPane sc2 = new JScrollPane(text2,22,32);

JComboBox cb1 = null;

JComboBox cb2 = new JComboBox( new String[] {"常规","粗体","斜体","粗斜体"} );

JComboBox cb3 = new JComboBox();

DefaultListModel listmod = new DefaultListModel();

JList jlist = new JList(listmod);

JScrollPane sc3 = new JScrollPane(jlist,22,32);

JTextField textin = new JTextField(52);

JButton btn1 = new JButton("发送");

JButton btn2 = new JButton("表情");

JButton btn3 = new JButton("颜色");

JSplitPane sp1 = new JSplitPane(1);

JSplitPane sp2 = new JSplitPane(0);

JSplitPane sp0 = new JSplitPane(0);

Font font = new Font("宋体",1,12);

Font[] font_array; String[] font_name;

ImagePane impan = new ImagePane(this,"d:/temp/qq/face/");/*——这个路径改成你的QQ\Face目录*/

Socket sock = null;

String ins = "", name= "no", sayto = "";

OutputStream o = null;

InputStream in = null;

PrintStream out = null;

BufferedReader bin = null;

Thread client_thread = null;

public void send(String s){

try{

out.println( s ); out.flush();

}catch(Exception e){

System.out.println("发送失败!");

}

}

public void run(){/*接收消息的线程*/

try{ int t=0;

send ("#name="+name); /*首先报上自己的名字*/

while(t++256){

if(sock!=null) {

ins = bin.readLine();/*=======以下为一系列的判断过程=======*/

if(ins.contains("quit")) break;

if(ins.contains("rept")) {

System.out.println("名字有重复!请换个名字登录!"); break;

}

int add=ins.indexOf("#add="); /*===判断是否为添加好友信息===*/

if(add!=-1){

String [] ad = ins.substring(add+5).split("#");

ins = ad[0] + "朋友进入了聊天室!"; listmod.clear();

for(String name : ad)

if(name!=null)listmod.addElement(name);

}

int quit=ins.indexOf("#exit=");/*===判断是否为好友退出信息===*/

if(quit!=-1){

String qs = ins.substring(quit+6);

ins = qs + "朋友离开了聊天室!";

listmod.removeElement(qs);

}

int ito = ins.indexOf("#icon=");

if(ito!=-1){

int index = Integer.parseInt(ins.substring(ito+6));

Icon icon = impan.getIcon(index);

text1.setSelectionStart(text1.getText().length());

if(icon!=null)text1.insertIcon(icon);

}

int sto= ins.indexOf("#sayto=");/*===判断谁对谁说===*/

if(sto!=-1){

int f=ins.indexOf("#", sto+7);

String s = ins.substring(0, sto);

String b = ins.substring(sto+7, f);

String a = ins.substring(f + 1);

if(b.equals(this.name)){

ins = a + "对你说:" + s;

text2.setText(text2.getText()+"\n"+ ins );

} else {

ins = a + "对" + b + "说:" + s;

text1.setText(text1.getText()+"\n" +ins);

}

}

} else break;

}

out.close(); bin.close(); in.close();o.close();sock.close(); System.exit(0);

}catch(Exception e){

System.out.println("client close error!\t" + e);

}

}

/*=================构造函数=================*/

Pane(InetAddress ip, int port,String name){

try{

this.name = name; sock = new Socket(ip, port);

in = sock.getInputStream();

o = sock.getOutputStream();

bin = new BufferedReader( new InputStreamReader( in ) );

out = new PrintStream ( o );

client_thread = new Thread(this); client_thread.start();

}catch(Exception e){

System.out.println("连接服务器错误!\t" + e); System.exit(0);

}

setTitle("欢迎您:" + name );

GraphicsEnvironment fm = GraphicsEnvironment.getLocalGraphicsEnvironment();font_name = fm.getAvailableFontFamilyNames();

cb1 = new JComboBox(font_name);for(int i=6;i=64;i++)cb3.addItem(i);

sp0.setTopComponent(sc1);sp0.setBottomComponent(sc2);sp0.setDividerLocation(280);sp1.setLeftComponent(sp0);

sp1.setRightComponent(sc3);sp1.setDividerLocation(432);sp2.setTopComponent(sp1);getContentPane().setBackground(new Color(131,172,113));

JPanel pan2 = new JPanel(new GridLayout(1,6));pan2.add(btn1);pan2.add(btn2);pan2.add(btn3);pan2.add(cb1);pan2.add(cb2);pan2.add(cb3);

textin.addActionListener(this);btn1.addActionListener(this);btn2.addActionListener(this);btn3.addActionListener(this);

cb1.addActionListener(this);cb2.addActionListener(this);cb3.addActionListener(this);sp2.setBottomComponent(pan2);sp2.setDividerLocation(442);add(sp2,"Center"); add(textin,"South"); setResizable(false);

jlist.setSelectedIndex(0); sp1.setOneTouchExpandable(true);sp0.setOneTouchExpandable(true);

jlist.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent e)

{

sayto = jlist.getSelectedValue().toString();

}});

addWindowListener( new WindowAdapter(){

public void windowClosing(WindowEvent e){

send("quit");

}});

}

public void actionPerformed(ActionEvent e){

Object o = e.getSource();

String txts = textin.getText(), vals =text1.getText();

if(o==textin)/*发送事件*/

{

send (txts+"#sayto="+sayto); textin.setText(null);

}else if(o==btn1){

}else if(o==btn2){

impan.setVisible(true);

Icon icon = impan.getIcon();

text1.setSelectionStart(text1.getText().length());

if(icon!=null)text1.insertIcon(icon);

send("#icon=" + impan.getFace() );

}else if(o==cb1||o==cb2||o==cb3){

String fontname = String.valueOf(cb1.getSelectedItem());

int style = cb2.getSelectedIndex();

int size = 6 + cb3.getSelectedIndex();

Font font = new Font(fontname,style,size);

text1.setFont(font);

text2.setFont(font);

}

}

public static void main(String[] ag){

String name =null;PrintStream out = System.out;

Random r = new Random();

Scanner sc = new Scanner(System.in);out.print("昵称:");

while((name=sc.next()).length()2)out.print("昵称:");

try{ /*————服务器主机名——端口号——昵称——*/

Pane pan = new Pane(InetAddress.getLocalHost(),6000,name);

if(pan!=null){

pan.setBounds(r.nextInt(200),r.nextInt(100),520,520);

pan.setVisible(true);

}

}catch(IOException e){ System.out.println("连接失败:" + e ); }

}

}

急求JavaC/S聊天室代码,有界面,可发消息传文件,非常感谢

客户端:importjava.awt.BorderLayout;importjava.awt.Color;importjava.awt.GridLayout;importjava.awt.Toolkit;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.util.HashMap;importjava.util.Map;importjava.util.StringTokenizer;importjavax.swing.DefaultListModel;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JList;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JSplitPane;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.border.TitledBorder;publicclassClient{privateJFrameframe;privateJListuserList;privateJTextAreatextArea;privateJTextFieldtextField;privateJTextFieldtxt_port;privateJTextFieldtxt_hostIp;privateJTextFieldtxt_name;privateJButtonbtn_start;privateJButtonbtn_stop;privateJButtonbtn_send;privateJPanelnorthPanel;privateJPanelsouthPanel;privateJScrollPanerightScroll;privateJScrollPaneleftScroll;privateJSplitPanecenterSplit;privateDefaultListModellistModel;privatebooleanisConnected=false;privateSocketsocket;privatePrintWriterwriter;privateBufferedReaderreader;privateMessageThreadmessageThread;//负责接收消息的线程privateMaponLineUsers=newHashMap();//所有在线用户//主方法,程序入口publicstaticvoidmain(String[]args){newClient();}//执行发送publicvoidsend(){if(!isConnected){JOptionPane.showMessageDialog(frame,"还没有连接服务器,无法发送消息!","错误",JOptionPane.ERROR_MESSAGE);return;}Stringmessage=textField.getText().trim();if(message==null||message.equals("")){JOptionPane.showMessageDialog(frame,"消息不能为空!","错误",JOptionPane.ERROR_MESSAGE);return;}sendMessage(frame.getTitle()+"@"+"ALL"+"@"+message);textField.setText(null);}//构造方法publicClient(){textArea=newJTextArea();textArea.setEditable(false);textArea.setForeground(Color.blue);textField=newJTextField();txt_port=newJTextField("719");txt_hostIp=newJTextField("127.0.0.1");txt_name=newJTextField("Lei");btn_start=newJButton("连接");btn_stop=newJButton("断开");btn_send=newJButton("发送");listModel=newDefaultListModel();userList=newJList(listModel);northPanel=newJPanel();northPanel.setLayout(newGridLayout(1,7));northPanel.add(newJLabel("端口"));northPanel.add(txt_port);northPanel.add(newJLabel("服务器IP"));northPanel.add(txt_hostIp);northPanel.add(newJLabel("姓名"));northPanel.add(txt_name);northPanel.add(btn_start);northPanel.add(btn_stop);northPanel.setBorder(newTitledBorder("连接信息"));rightScroll=newJScrollPane(textArea);rightScroll.setBorder(newTitledBorder("消息显示区"));leftScroll=newJScrollPane(userList);leftScroll.setBorder(newTitledBorder("在线用户"));southPanel=newJPanel(newBorderLayout());southPanel.add(textField,"Center");southPanel.add(btn_send,"East");southPanel.setBorder(newTitledBorder("写消息"));centerSplit=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftScroll,rightScroll);centerSplit.setDividerLocation(100);frame=newJFrame("客户机");//更改JFrame的图标://frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));frame.setLayout(newBorderLayout());frame.add(northPanel,"North");frame.add(centerSplit,"Center");frame.add(southPanel,"South");frame.setSize(600,400);intscreen_width=Toolkit.getDefaultToolkit().getScreenSize().width;intscreen_height=Toolkit.getDefaultToolkit().getScreenSize().height;frame.setLocation((screen_width-frame.getWidth())/2,(screen_height-frame.getHeight())/2);frame.setVisible(true);//写消息的文本框中按回车键时事件textField.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){send();}});//单击发送按钮时事件btn_send.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){send();}});//单击连接按钮时事件btn_start.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){intport;if(isConnected){JOptionPane.showMessageDialog(frame,"已处于连接上状态,不要重复连接!","错误",JOptionPane.ERROR_MESSAGE);return;}try{try{port=Integer.parseInt(txt_port.getText().trim());}catch(NumberFormatExceptione2){thrownewException("端口号不符合要求!端口为整数!");}StringhostIp=txt_hostIp.getText().trim();Stringname=txt_name.getText().trim();if(name.equals("")||hostIp.equals("")){thrownewException("姓名、服务器IP不能为空!");}booleanflag=connectServer(port,hostIp,name);if(flag==false){thrownewException("与服务器连接失败!");}frame.setTitle(name);JOptionPane.showMessageDialog(frame,"成功连接!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//单击断开按钮时事件btn_stop.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){if(!isConnected){JOptionPane.showMessageDialog(frame,"已处于断开状态,不要重复断开!","错误",JOptionPane.ERROR_MESSAGE);return;}try{booleanflag=closeConnection();//断开连接if(flag==false){thrownewException("断开连接发生异常!");}JOptionPane.showMessageDialog(frame,"成功断开!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);}}});//关闭窗口时事件frame.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){if(isConnected){closeConnection();//关闭连接}System.exit(0);//退出程序}});}/***连接服务器**@paramport*@paramhostIp*@paramname*/publicbooleanconnectServer(intport,StringhostIp,Stringname){//连接服务器try{socket=newSocket(hostIp,port);//根据端口号和服务器ip建立连接writer=newPrintWriter(socket.getOutputStream());reader=newBufferedReader(newInputStreamReader(socket.getInputStream()));//发送客户端用户基本信息(用户名和ip地址)sendMessage(name+"@"+socket.getLocalAddress().toString());//开启接收消息的线程messageThread=newMessageThread(reader,textArea);messageThread.start();isConnected=true;//已经连接上了returntrue;}catch(Exceptione){textArea.append("与端口号为:"+port+"IP地址为:"+hostIp+"的服务器连接失败!"+"\r\n");isConnected=false;//未连接上returnfalse;}}/***发送消息**@parammessage*/publicvoidsendMessage(Stringmessage){writer.println(message);writer.flush();}/***客户端主动关闭连接*/@SuppressWarnings("deprecation")publicsynchronizedbooleancloseConnection(){try{sendMessage("CLOSE");//发送断开连接命令给服务器messageThread.stop();//停止接受消息线程//释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;returntrue;}catch(IOExceptione1){e1.printStackTrace();isConnected=true;returnfalse;}}//不断接收消息的线程classMessageThreadextendsThread{privateBufferedReaderreader;privateJTextAreatextArea;//接收消息线程的构造方法publicMessageThread(BufferedReaderreader,JTextAreatextArea){this.reader=reader;this.textArea=textArea;}//被动的关闭连接publicsynchronizedvoidcloseCon()throwsException{//清空用户列表listModel.removeAllElements();//被动的关闭连接释放资源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;//修改状态为断开}publicvoidrun(){Stringmessage="";while(true){try{message=reader.readLine();StringTokenizerstringTokenizer=newStringTokenizer(message,"/@");Stringcommand=stringTokenizer.nextToken();//命令if(command.equals("CLOSE"))//服务器已关闭命令{textArea.append("服务器已关闭!\r\n");closeCon();//被动的关闭连接return;//结束线程}elseif(command.equals("ADD")){//有用户上线更新在线列表Stringusername="";StringuserIp="";if((username=stringTokenizer.nextToken())!=null(userIp=stringTokenizer.nextToken())!=null){Useruser=newUser(username,userIp);onLineUsers.put(username,user);listModel.addElement(username);}}elseif(command.equals("DELETE")){//有用户下线更新在线列表Stringusername=stringTokenizer.nextToken();Useruser=(User)onLineUsers.get(username);onLineUsers.remove(user);listModel.removeElement(username);}elseif(command.equals("USERLIST")){//加载在线用户列表intsize=Integer.parseInt(stringTokenizer.nextToken());Stringusername=null;StringuserIp=null;for(inti=0;i

急求一个简易聊天室的代码

这个应该可以的拉:

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(j0) 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("BL 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 during 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;iclients.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;iclients.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聊天室程序源代码 java聊天程序设计代码
地址分享:http://kswjz.com/article/hpgdpo.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流