import java.util.*;
桓臺網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站,桓臺網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為桓臺上千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的桓臺做網(wǎng)站的公司定做!
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[] {"常規(guī)","粗體","斜體","粗斜體"} );
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("發(fā)送");
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("發(fā)送失敗!");
}
}
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("名字有重復(fù)!請換個名字登錄!"); 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);
}
}
/*=================構(gòu)造函數(shù)=================*/
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("連接服務(wù)器錯誤!\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)/*發(fā)送事件*/
{
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{ /*————服務(wù)器主機名——端口號——昵稱——*/
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 ); }
}
}
客戶端: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;//負責(zé)接收消息的線程privateMaponLineUsers=newHashMap();//所有在線用戶//主方法,程序入口publicstaticvoidmain(String[]args){newClient();}//執(zhí)行發(fā)送publicvoidsend(){if(!isConnected){JOptionPane.showMessageDialog(frame,"還沒有連接服務(wù)器,無法發(fā)送消息!","錯誤",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);}//構(gòu)造方法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("發(fā)送");listModel=newDefaultListModel();userList=newJList(listModel);northPanel=newJPanel();northPanel.setLayout(newGridLayout(1,7));northPanel.add(newJLabel("端口"));northPanel.add(txt_port);northPanel.add(newJLabel("服務(wù)器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("消息顯示區(qū)"));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();}});//單擊發(fā)送按鈕時事件btn_send.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){send();}});//單擊連接按鈕時事件btn_start.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){intport;if(isConnected){JOptionPane.showMessageDialog(frame,"已處于連接上狀態(tài),不要重復(fù)連接!","錯誤",JOptionPane.ERROR_MESSAGE);return;}try{try{port=Integer.parseInt(txt_port.getText().trim());}catch(NumberFormatExceptione2){thrownewException("端口號不符合要求!端口為整數(shù)!");}StringhostIp=txt_hostIp.getText().trim();Stringname=txt_name.getText().trim();if(name.equals("")||hostIp.equals("")){thrownewException("姓名、服務(wù)器IP不能為空!");}booleanflag=connectServer(port,hostIp,name);if(flag==false){thrownewException("與服務(wù)器連接失敗!");}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,"已處于斷開狀態(tài),不要重復(fù)斷開!","錯誤",JOptionPane.ERROR_MESSAGE);return;}try{booleanflag=closeConnection();//斷開連接if(flag==false){thrownewException("斷開連接發(fā)生異常!");}JOptionPane.showMessageDialog(frame,"成功斷開!");}catch(Exceptionexc){JOptionPane.showMessageDialog(frame,exc.getMessage(),"錯誤",JOptionPane.ERROR_MESSAGE);}}});//關(guān)閉窗口時事件frame.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){if(isConnected){closeConnection();//關(guān)閉連接}System.exit(0);//退出程序}});}/***連接服務(wù)器**@paramport*@paramhostIp*@paramname*/publicbooleanconnectServer(intport,StringhostIp,Stringname){//連接服務(wù)器try{socket=newSocket(hostIp,port);//根據(jù)端口號和服務(wù)器ip建立連接writer=newPrintWriter(socket.getOutputStream());reader=newBufferedReader(newInputStreamReader(socket.getInputStream()));//發(fā)送客戶端用戶基本信息(用戶名和ip地址)sendMessage(name+"@"+socket.getLocalAddress().toString());//開啟接收消息的線程messageThread=newMessageThread(reader,textArea);messageThread.start();isConnected=true;//已經(jīng)連接上了returntrue;}catch(Exceptione){textArea.append("與端口號為:"+port+"IP地址為:"+hostIp+"的服務(wù)器連接失敗!"+"\r\n");isConnected=false;//未連接上returnfalse;}}/***發(fā)送消息**@parammessage*/publicvoidsendMessage(Stringmessage){writer.println(message);writer.flush();}/***客戶端主動關(guān)閉連接*/@SuppressWarnings("deprecation")publicsynchronizedbooleancloseConnection(){try{sendMessage("CLOSE");//發(fā)送斷開連接命令給服務(wù)器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;//接收消息線程的構(gòu)造方法publicMessageThread(BufferedReaderreader,JTextAreatextArea){this.reader=reader;this.textArea=textArea;}//被動的關(guān)閉連接publicsynchronizedvoidcloseCon()throwsException{//清空用戶列表listModel.removeAllElements();//被動的關(guān)閉連接釋放資源if(reader!=null){reader.close();}if(writer!=null){writer.close();}if(socket!=null){socket.close();}isConnected=false;//修改狀態(tài)為斷開}publicvoidrun(){Stringmessage="";while(true){try{message=reader.readLine();StringTokenizerstringTokenizer=newStringTokenizer(message,"/@");Stringcommand=stringTokenizer.nextToken();//命令if(command.equals("CLOSE"))//服務(wù)器已關(guān)閉命令{textArea.append("服務(wù)器已關(guān)閉!\r\n");closeCon();//被動的關(guān)閉連接return;//結(jié)束線程}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
這個應(yīng)該可以的拉:
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Applet{
protected boolean loggedIn;//登入狀態(tài)
protected Frame cp;//聊天室框架
protected static int PORTNUM=7777; //缺省端口號7777
protected int port;//實際端口號
protected Socket sock;
protected BufferedReader is;//用于從sock讀取數(shù)據(jù)的BufferedReader
protected PrintWriter pw;//用于向sock寫入數(shù)據(jù)的PrintWriter
protected TextField tf;//用于輸入的TextField
protected TextArea ta;//用于顯示對話的TextArea
protected Button lib;//登入按鈕
protected Button lob;//登出的按鈕
final static String TITLE ="Chatroom applet";
protected String paintMessage;//發(fā)表的消息
public ChatParameter Chat;
public void init(){
paintMessage="正在生成聊天窗口";
repaint();
cp=new Frame(TITLE);
cp.setLayout(new BorderLayout());
String portNum=getParameter("port");//呢個參數(shù)勿太明
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){
//如果執(zhí)行了setVisible或者dispose,關(guān)閉窗口
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;}
//構(gòu)造并且啟動讀入器,從服務(wù)器讀取數(shù)據(jù),輸出到文本框中
//這里,長成一個線程來避免鎖住資源(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();
//假定登錄(其實只是打印相關(guān)信息,并沒有真正登錄)
// 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){
// 異常處理哦
}
}
//沒有設(shè)置stop的方法,即使從瀏覽器跳到另外一個網(wǎng)頁的時候
//聊天程序還可以繼續(xù)運行
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);
}
}
聊天室服務(wù)器端
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer{
//聊天室管理員ID
protected final static String CHATMASTER_ID="ChatMaster";
//系統(tǒng)信息的分隔符
protected final static String SEP=": ";
//服務(wù)器的Socket
protected ServerSocket servSock;
//當(dāng)前客戶端列表
protected ArrayList clients;
//調(diào)試標記
protected boolean DEBUG=false;
public ChatParameter Chat;
//主方法構(gòu)造一個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");
}
//構(gòu)造和運行一個聊天服務(wù)
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);
}
//處理會話的內(nèi)部的類
protected class ChatHandler extends Thread {
//客戶端scoket
protected Socket clientSock;
//讀取socket的BufferedReader
protected BufferedReader is ;
//在socket 上發(fā)送信息行的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結(jié)束
// 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 結(jié)束,我們完成了
//還不能發(fā)送再見的消息
//得有簡單的基于命令的協(xié)議才行
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);
}
}
//發(fā)送一條消息給用戶
public void send(String sender,String mesg){
pw.println(sender+SEP+"*"+mesg);
}
//發(fā)送私有的消息
protected void psend(String sender ,String msg){
send("*"+sender+"*",msg);
}
//發(fā)送一條消息給所有的用戶
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對象轉(zhuǎn)換成一個字符串
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){
}
}
記得加分啊!!!
當(dāng)前題目:java聊天室程序源代碼 java聊天程序設(shè)計代碼
分享URL:http://vcdvsql.cn/article30/hpgdpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、ChatGPT、手機網(wǎng)站建設(shè)、服務(wù)器托管、外貿(mào)建站、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)