版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、JAVA小型聊天室下載必讀:1、要在工程里新建perties以及perties的配置文件serverhost和serverport分別為服務(wù)器所在計(jì)算機(jī)的IP和端口:perties:serverhost=loaclhostserverport=8088perties:serverhost=loaclhostserverport=80892、 先啟動聊天室消息服務(wù)器ChatServer和登錄服務(wù)器LoginServer3、 然后啟動登錄客戶端Login4、 先注冊,注冊后要重啟登錄服務(wù)器,然后再登錄才不會出錯(小bug不
2、想修改了,可自行修改)5、 聊天室目前實(shí)行了登錄界面和聊天界面,可自行開發(fā)注冊界面等6、 聊天室目前只實(shí)現(xiàn)了公聊、私聊、好友列表刷新、上下線提醒等功能。可自行添加其他功能7、 用戶信息目前只開發(fā)了昵稱和密碼兩個屬性,可自行開發(fā)其他屬性源代碼:1、 聊天室消息服務(wù)器ChatServer:import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import .InetAddress;import .Serve
3、rSocket;import .Socket;import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/* * 聊天室消息接收發(fā)送服務(wù)器 * author Among * */public class ChatServer private ServerSocket server;private Map<String,PrintWriter>PW
4、;/存儲每個線程的輸出流private Map<String,String>user;/存儲每個用戶信息private ExecutorService threadPool;/線程池private static final String personalChat="11110001"/私聊標(biāo)識private static final String publicChat="11110010"/公聊標(biāo)識private static final String Online="11110011"/上線標(biāo)識private stati
5、c final String SigningOff="11110100"/下線標(biāo)識private static final String friendSign="11110101"/好友列表請求標(biāo)識/* * 構(gòu)造方法 * 初始化 */public ChatServer()try server=new ServerSocket(8088);/打開新的服務(wù)端接口PW=new HashMap<String,PrintWriter>();user=new HashMap<String,String>();threadPool=Execut
6、ors.newFixedThreadPool(50); catch (Exception e) e.printStackTrace();/* * 添加輸出流方法,并添加同步互斥鎖 * param name * param pw */private synchronized void addPw(String name,PrintWriter pw)PW.put(name,pw);/* * 刪除輸出流方法,添加同步互斥鎖 * param name * param pw */private synchronized void removePw(String name,PrintWriter pw)
7、PW.remove(name, pw);/* * 遍歷輸出流,群發(fā)消息 * 添加同步互斥鎖 * param msg */private synchronized void sendMsgtoAll(String msg)Set<String>names=PW.keySet();for(String name:names)PW.get(name).println(msg);/* * 服務(wù)器啟動方法 * 打開接收器,并把連接進(jìn)來的socket交給線程開始聊天 */public void start()try while(true)System.out.println("等到客
8、戶端連接.");Socket socket=server.accept();System.out.println("一個客戶端連接了!");/啟動一個線程來處理新連接ClientHandler handler=new ClientHandler(socket);threadPool.execute(handler); catch (Exception e) /* * 線程 * 用于和每個連接進(jìn)來的socket交互 */class ClientHandler implements Runnableprivate Socket socket;private Strin
9、g host;private int port;private PrintWriter pw=null;private String name;private BufferedReader br;private String Name;/* * 構(gòu)造方法 * 獲取連接進(jìn)來的socket信息 * param socket */public ClientHandler(Socket socket)InetAddress address=socket.getInetAddress();host=address.getHostAddress();port=socket.getPort();System
10、.out.println(host+port+"上線了。當(dāng)前在線人數(shù):"+(PW.size()+1);this.socket=socket;/* * 線程run方法 * 獲取socket輸入輸出流 * 1、讀取用戶名稱 * 2、判斷消息標(biāo)識符 * 3、接收并處理消息 * 4、發(fā)送消息標(biāo)識符 * 5、發(fā)送消息 */public void run()trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),true);br=new BufferedReader(new InputStreamRea
11、der(socket.getInputStream();name=br.readLine();user.put(name, name);addPw(name,pw);String message=null;/sendMsgtoAll(name+"上線了。當(dāng)前在線人數(shù):"+PW.size();while(message=br.readLine()!=null)if(Online.equals(message)sendMsgtoAll(Online);sendMsgtoAll(name);else if(publicChat.equals(message)message=br.
12、readLine();sendMsgtoAll(publicChat);sendMsgtoAll(name+"說:"+message);System.out.println(name+message);else if(SigningOff.equals(message)/message=br.readLine();/System.out.println(name+message);sendMsgtoAll(SigningOff);sendMsgtoAll(name+"下線了。當(dāng)前在線人數(shù):"+(PW.size()-1);System.out.printl
13、n(name+"下線了。當(dāng)前在線人數(shù):"+(PW.size()-1);user.remove(name);/刪除下線用戶removePw(name,pw);/刪除下線用戶的輸出流socket.close();else if(personalChat.equals(message)message=br.readLine();String msg=message.split(":");PW.get(msg0).println(personalChat);PW.get(msg0).println(name+"悄悄對你說:"+msg1);PW
14、.get(name).println(personalChat);PW.get(name).println("你悄悄對"+msg0+"說:"+msg1);else if(friendSign.equals(message)String msgs=""Set<String>names=user.keySet();for(String n:names)Name=user.get(n);msgs+=Name+":"System.out.println(msgs);sendMsgtoAll(friendSign
15、);sendMsgtoAll(msgs);catch(Exception e)/e.printStackTrace();/*main方法*/public static void main(String args) ChatServer server=new ChatServer();server.start();2、 聊天室登錄服務(wù)器LoginServer:import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWri
16、ter;import .ServerSocket;import .Socket;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/* * 聊天室登錄服務(wù)器 * 接收和發(fā)送登錄注冊信息 * author Among * version 1.0
17、*/public class LoginServer private static final String checkLogin="11110110"/檢查登錄信息標(biāo)識private static final String Correct="11111111"/信息正確標(biāo)識private static final String Wrong="00000000"/信息錯誤標(biāo)識private static final String Regist="11110111"/注冊標(biāo)識private ServerSocket
18、server;private ExecutorService threadPool;private List<User>user=new ArrayList<User>();private Map<String,String>login;private Save save=new Save();private Iterator<User>it;private User user0=null;/* * 構(gòu)造方法 * 打開監(jiān)聽接口 * 初始化 */public LoginServer()try server=new ServerSocket(8089
19、);threadPool=Executors.newFixedThreadPool(50);user=save.ReadData();it=user.iterator();login=new HashMap<String,String>();while(it.hasNext()user0=it.next();if(user0=null)continue;login.put(user0.getName(),user0.getPassword(); catch (Exception e) e.printStackTrace();/* * 登錄服務(wù)器啟動方法 * 接收socket連接 *
20、 建立線程處理信息 */public void start()trywhile(true)System.out.println("等待一個登陸客戶端.");Socket socket=server.accept();System.out.println("登陸客戶端已連接!");threadPool.execute(new LoginHandler(socket);catch(Exception e)e.printStackTrace();/* * 交互信息處理線程 * 1、獲取輸入輸出流 * 2、判斷消息標(biāo)識 * 3、接收消息 * 4、處理消息 * 5
21、、發(fā)送消息標(biāo)識 * 6、發(fā)送處理結(jié)果 */class LoginHandler implements Runnableprivate Socket socket;public BufferedReader br;public PrintWriter pw;public String logins; public User users;public LoginHandler(Socket socket)this.socket=socket;Override/* * 線程run方法 */public void run() try br=new BufferedReader(new InputStr
22、eamReader(socket.getInputStream(),"utf-8");pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);String message=null;while(message=br.readLine()!=null)System.out.println(message);if(checkLogin.equals(message)message=br.readLine();System.out.println(mes
23、sage);logins=message.split(":");System.out.println(logins0+","+logins1);System.out.println(user.toString();System.out.println();if(logins1.equals(login.get(logins0)pw.println(Correct);elsepw.println(Wrong);else if(Regist.equals(message)message=br.readLine();System.out.println(mes
24、sage); logins=message.split(":");System.out.println(logins0+","+logins1);System.out.println(user.toString();if(login.containsKey(logins0)pw.println(Wrong);elsepw.println(Correct);user.add(new User(logins0,logins1);save.SaveData(user); catch (Exception e) / TODO: handle exception/
25、* * main方法 * param args */public static void main(String args) LoginServer server=new LoginServer();server.start();3、 聊天室登錄界面Login:import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.FileInputStream;import jav
26、a.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import .Socket;import java.util.Properties;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import
27、javax.swing.border.TitledBorder;/* * 聊天室登錄界面 * 客戶端啟動處 * author Among * version 1.0 */public class Login implements ActionListenerprivate static final String checkLogin="11110110"/檢查登錄信息標(biāo)識private static final String Correct="11111111"/信息正確標(biāo)識private static final String Regist="
28、;11110111"/注冊標(biāo)識private static Socket socket;private static PrintWriter pw;private static BufferedReader br;private JFrame frame=new JFrame("登錄");private JPanel jp1=new JPanel();private JPanel jp2=new JPanel();private JPanel jp3=new JPanel();private JPanel jp4=new JPanel();private JLab
29、el jl1=new JLabel("賬號:");private JLabel jl2=new JLabel("密碼:");private JTextField jtf1=new JTextField(15);private JTextField jtf2=new JTextField(15);private JButton jb1=new JButton("登錄");private JButton jb2=new JButton("注冊");SuppressWarnings("unused")
30、private TitledBorder tb=new TitledBorder("");/* * 啟動界面方法 */public void init()jb1.addActionListener(this);jb2.addActionListener(this);jp1.add(jl1);jp1.add(jtf1);jp2.add(jl2);jp2.add(jtf2);jp3.add(jb1);jp3.add(jb2);jp4.setLayout(new GridLayout(3,1);jp4.add(jp1);jp4.add(jp2);jp4.add(jp3);fram
31、e.add(jp4);frame.setLocation(532,265);frame.setSize(300, 180);frame.setResizable(false);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);/* * 構(gòu)造方法 * 讀取配置文件 * 和登錄服務(wù)器建立socket連接 */public Login()try Properties p=new Properties();p.load(new FileInputStream("pertie
32、s");String address=p.getProperty("serverhost");int port=Integer.parseInt(p.getProperty("serverport");socket=new Socket(address,port); catch (Exception e) e.printStackTrace();/* * main方法 * param args */public static void main(String args) Login login=new Login();login.init();
33、/* * Override * 界面監(jiān)聽方法 * 1、獲取輸入框消息 * 2、判斷按鈕監(jiān)聽結(jié)果 * 3、發(fā)送消息標(biāo)識 * 4、發(fā)送消息標(biāo)識 * 5、接收消息 * 6、判斷接收消息 * 7、處理結(jié)果 */SuppressWarnings("static-access")public void actionPerformed(ActionEvent e) String ID;String PassWord;if(e.getActionCommand().equals("注冊")ID=jtf1.getText();PassWord=jtf2.getText()
34、;if(ID.equals("")JOptionPane.showMessageDialog(null, "請輸入賬號!");else if(PassWord.equals("")JOptionPane.showMessageDialog(null, "請輸入密碼!");else trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);pw.println(Regist);pw.pr
35、intln(ID+":"+PassWord);br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8");SuppressWarnings("unused")String msg;if(Correct.equals(msg=br.readLine()JOptionPane.showMessageDialog(null, "注冊成功!");elseJOptionPane.showMessageDialog(null, &qu
36、ot;賬號已存在!");catch(Exception ee)ee.printStackTrace();else if(e.getActionCommand().equals("登錄")ID=jtf1.getText();PassWord=jtf2.getText();if(ID.equals("")JOptionPane.showMessageDialog(null, "請輸入賬號!");else if(PassWord.equals("")JOptionPane.showMessageDialog(n
37、ull, "請輸入密碼!");else trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);pw.println(checkLogin);pw.println(ID+":"+PassWord);br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8");SuppressWarnings("unus
38、ed")String msg;if(Correct.equals(msg=br.readLine()/System.out.println(msg);JOptionPane.showMessageDialog(null, "登錄成功!");frame.dispose();ChatSurface CSf=new ChatSurface();/創(chuàng)建聊天界面CSf.user=new User(ID,PassWord);CSf.GetSurface();/打開登錄界面CSf.getSocket();/和聊天服務(wù)器建立連接else JOptionPane.showMessa
39、geDialog(null, "密碼錯誤,請重新登陸!");catch(Exception ee)4、 聊天室聊天界面ChatSurface:import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowE
40、vent;import java.io.OutputStreamWriter;import java.io.PrintWriter;import javax.swing.DefaultListModel;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JPanel;import jav
41、ax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.ListSelectionModel;import javax.swing.ScrollPaneConstants;import javax.swing.border.TitledBorder;/* * 聊天室聊天界面 * author Among * version 1.0 */public class ChatSurface implements ActionListenerprivate st
42、atic final String personalChat="11110001"/私聊標(biāo)識private static final String publicChat="11110010"/公聊標(biāo)識private static final String Online="11110011"/上線標(biāo)識private static final String SigningOff="11110100"/下線標(biāo)識private static final String friendSign="11110101&qu
43、ot;/好友列表請求標(biāo)識private JFrame jf=new JFrame("聊天室");private static ChatClient client;private PrintWriter pw;public static User user;public ChatSurface() /設(shè)置窗口關(guān)閉事件,如果點(diǎn)擊窗口右上角叉號關(guān)閉,執(zhí)行下邊程序jf.addWindowListener( new WindowAdapter()public void windowClosing(WindowEvent e)try pw=new PrintWriter(client.
44、socket.getOutputStream(),true);pw.println(SigningOff);/發(fā)送下線標(biāo)識pw.println(friendSign);/jf.dispose();/關(guān)閉窗口System.exit(0);/退出catch(Exception ex) );public JPanel jp1=new JPanel();public JPanel jp2=new JPanel();public JPanel jp3=new JPanel();public JPanel jp4=new JPanel();public JPanel jp5=new JPanel();pu
45、blic JPanel jp6=new JPanel();public JPanel jp7=new JPanel();public static JTextArea jta1=new JTextArea(12,42);/開辟公聊界面public static JTextArea jta2=new JTextArea(12,42);/開辟私聊界面public JLabel jl1=new JLabel("對");SuppressWarnings("rawtypes")public static JComboBox jcomb=new JComboBox(
46、);public JCheckBox jcb=new JCheckBox("私聊");public JTextField jtf=new JTextField(36);public JButton jb1=new JButton("發(fā)送>>");SuppressWarnings("rawtypes")public static DefaultListModel listModel1;SuppressWarnings("rawtypes")public static JList lst1;/* * 獲取聊
47、天界面方法 */SuppressWarnings( "unchecked", "rawtypes" )public void GetSurface()jcomb.addItem("所有人");/this.na=name;/this.se=sex;jta1.setEditable(false);jta2.setEditable(false);listModel1= new DefaultListModel();lst1 = new JList(listModel1);lst1.setSelectionMode(ListSelection
48、Model.SINGLE_SELECTION);lst1.setVisibleRowCount(18);lst1.setFixedCellHeight(28);lst1.setFixedCellWidth(100);JScrollPane jsp1=new JScrollPane(jta1);JScrollPane jsp2=new JScrollPane(jta2);JScrollPane jsp3=new JScrollPane(lst1);jsp3.setBorder(new TitledBorder("好友列表");jsp1.setBorder(new Titled
49、Border("主聊天頻道");jsp2.setBorder(new TitledBorder("我的頻道");jp1.setLayout(new GridLayout(2,1);jp1.add(jsp1);jp1.add(jsp2);jp2.setLayout(new FlowLayout(FlowLayout.LEFT);jp2.add(jl1);jp2.add(jcomb);jp2.add(jcb);jp3.setLayout(new FlowLayout(FlowLayout.LEFT);jp3.add(jtf);jp3.add(jb1);jp4
50、.setLayout(new GridLayout(2,1);jp4.add(jp2);jp4.add(jp3);jp5.setLayout(new BorderLayout();jp5.add(jp1,BorderLayout.NORTH);jp5.add(jp4,BorderLayout.SOUTH);jp6.setLayout(new BorderLayout();jp6.add(jsp3,BorderLayout.NORTH);jp7.setLayout(new FlowLayout(FlowLayout.LEFT);jp7.add(jp5);jp7.add(jp6);jf.add(j
51、p7);jf.setLocation(350,100);jf.setSize(700,650);jf.setResizable(false);jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);jf.setVisible(true);jb1.addActionListener(this);jta1.setLineWrap(true);jta2.setLineWrap(true);jsp1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
52、jsp1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jsp2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jsp2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jsp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jsp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jf.pack();/* * 獲取聊天socket的方法 * 向服務(wù)器發(fā)送連接消息 */pu
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年度年福建省高校教師資格證之高等教育法規(guī)提升訓(xùn)練試卷B卷附答案
- 2023年重鉻酸鈉資金籌措計(jì)劃書
- 中級經(jīng)濟(jì)師(運(yùn)輸經(jīng)濟(jì))《專業(yè)知識與實(shí)務(wù)》考前沖刺必會試題及答案
- 三年級數(shù)學(xué)(上)計(jì)算題專項(xiàng)練習(xí)附答案集錦
- 辦公用品質(zhì)量保證書
- 2024年公司遷移服務(wù)協(xié)議模板
- 村會議決議模板5篇
- 2024詳細(xì)土建工程承攬協(xié)議模板
- 2024年事業(yè)單位正式協(xié)議樣式
- 崗位聘任職責(zé)與權(quán)益詳解協(xié)議樣本
- 2024-2029全球及中國客戶服務(wù)BPO行業(yè)市場發(fā)展分析及前景趨勢與投資發(fā)展研究報告
- 24春國家開放大學(xué)《農(nóng)業(yè)推廣》調(diào)查報告參考答案
- 醫(yī)院開診儀式策劃方案
- 造口回納術(shù)護(hù)理
- 螃蟹水產(chǎn)養(yǎng)殖知識培訓(xùn)課件
- 過敏性休克的急救和處理專題醫(yī)學(xué)知識宣講培訓(xùn)課件
- 工業(yè)自動化中的生產(chǎn)柔性與響應(yīng)性制造
- 心理健康的重要性課件
- JC/T2055-2020 寵物墊圈用顆粒膨潤土
- 《西游記》第三回讀后感
- 抽油煙機(jī)控制系統(tǒng)的設(shè)計(jì)
評論
0/150
提交評論