Java實(shí)現(xiàn)簡(jiǎn)單局域網(wǎng)聊天室
本文實(shí)例為大家分享了Java實(shí)現(xiàn)簡(jiǎn)單局域網(wǎng)聊天室的具體代碼,供大家參考,具體內(nèi)容如下
Java 的Socket編程:1、TCP協(xié)議是面向連接的、可靠的、有序的、以字節(jié)流的方式發(fā)送數(shù)據(jù),通過(guò)三次握手方式建立連接,形成傳輸數(shù)據(jù)的通道,在連接中進(jìn)行大量數(shù)據(jù)的傳輸,效率會(huì)稍低
2、Java中基于TCP協(xié)議實(shí)現(xiàn)網(wǎng)絡(luò)通信的類
客戶端的Socket類 服務(wù)器端的ServerSocket類3、Socket通信的步驟
① 創(chuàng)建ServerSocket和Socket
② 打開(kāi)連接到Socket的輸入/輸出流
③ 按照協(xié)議對(duì)Socket進(jìn)行讀/寫操作
④ 關(guān)閉輸入輸出流、關(guān)閉Socket
4、服務(wù)器端:
① 創(chuàng)建ServerSocket對(duì)象,綁定監(jiān)聽(tīng)端口
② 通過(guò)accept()方法監(jiān)聽(tīng)客戶端請(qǐng)求
③ 連接建立后,通過(guò)輸入流讀取客戶端發(fā)送的請(qǐng)求信息
④ 通過(guò)輸出流向客戶端發(fā)送鄉(xiāng)音信息
⑤ 關(guān)閉相關(guān)資源
5、客戶端:
① 創(chuàng)建Socket對(duì)象,指明需要連接的服務(wù)器的地址和端口號(hào)
② 連接建立后,通過(guò)輸出流想服務(wù)器端發(fā)送請(qǐng)求信息
③ 通過(guò)輸入流獲取服務(wù)器響應(yīng)的信息
④ 關(guān)閉響應(yīng)資源
實(shí)現(xiàn)的聊天室例子:實(shí)現(xiàn)的效果是如下:
服務(wù)端代碼:
package socket.server; import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList; /** * @author 超 * Create by fengc on 2018/7/25 21:21 */public class Server extends Thread{ ServerUI ui; ServerSocket ss; BufferedReader reader; PrintWriter writer; public Server(ServerUI ui) {this.ui = ui;this.start(); } @Override public void run() {try { ss = new ServerSocket(8081); ui.clients=new ArrayList<>(); println('啟動(dòng)服務(wù)器成功:端口8081'); while (true) {println('等待客戶端鏈接.......................................');Socket client = ss.accept();ui.clients.add(client);println('連接成功,客戶端請(qǐng)求服務(wù)端的詳細(xì)信息:' + client.toString());new ListenerClient(ui, client); }} catch (IOException e) { println('啟動(dòng)服務(wù)器失?。憾丝?081'); println(e.toString()); e.printStackTrace();} } public synchronized void sendMsg(String msg) {try { for (int i = 0; i < ui.clients.size(); i++) {Socket client = ui.clients.get(i);writer = new PrintWriter(client.getOutputStream(), true);writer.println(msg); }} catch (Exception e) { println(e.toString());} } public void println(String s) {if (s != null) { s = '服務(wù)端打印消息:' + s; this.ui.taShow.setText(this.ui.taShow.getText() + s + 'n'); System.out.println(s + 'n');} } public void closeServer() {try { if (ss != null)ss.close(); if (reader != null)reader.close(); if (writer != null)writer.close();} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();} } }
package socket.server; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket; /** * @author 超 * Create by fengc on 2018/7/25 21:33 * 這個(gè)類是服務(wù)器端的等待客戶端發(fā)送信息* */public class ListenerClient extends Thread{ BufferedReader reader; PrintWriter writer; ServerUI ui; Socket client; public ListenerClient(ServerUI ui, Socket client) {this.ui = ui;this.client=client;this.start(); } //為每一個(gè)客戶端創(chuàng)建線程等待接收信息,然后把信息廣播出去 @Override public void run() {String msg = '';while (true) { try {reader = new BufferedReader(new InputStreamReader(client.getInputStream()));writer = new PrintWriter(client.getOutputStream(), true);msg = reader.readLine();sendMsg(msg); } catch (IOException e) {println(e.toString());break; } if (msg != null && msg.trim() != '') {println('客戶端 ' + msg); }} } //把信息廣播到所有用戶 public synchronized void sendMsg(String msg) {try { for (int i = 0; i < ui.clients.size(); i++) {Socket client = ui.clients.get(i);writer = new PrintWriter(client.getOutputStream(), true);writer.println(msg); } } catch (Exception e) { println(e.toString());} } public void println(String s) {if (s != null) { this.ui.taShow.setText(this.ui.taShow.getText() + s + 'n'); System.out.println(s + 'n');} }}
package socket.server; import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.net.Socket;import java.util.List; /** * @author 超 * Create by fengc on 2018/7/25 21:21 */public class ServerUI extends JFrame { public static void main(String[] args) {new ServerUI(); } public JButton btStart;//啟動(dòng)服務(wù)器 public JButton btSend;//發(fā)送信息按鈕 public JTextField tfSend;//需要發(fā)送的文本信息 public JTextArea taShow;//信息展示 public Server server;//用來(lái)監(jiān)聽(tīng)客戶端連接 static List<Socket> clients;//保存連接到服務(wù)器的客戶端 public ServerUI() {super('服務(wù)器端');btStart = new JButton('啟動(dòng)服務(wù)');btSend = new JButton('發(fā)送信息');tfSend = new JTextField(10); //裝在輸入文字taShow = new JTextArea();//點(diǎn)擊按鈕,所做的是事情,啟動(dòng)服務(wù)器btStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {server = new Server(ServerUI.this); }});//點(diǎn)擊發(fā)送消息按鈕btSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {server.sendMsg(tfSend.getText());tfSend.setText(''); }});//初始化界面this.addWindowListener(new WindowAdapter() { //關(guān)閉按鈕點(diǎn)擊事件 public void windowClosing(WindowEvent e) {int a = JOptionPane.showConfirmDialog(null, '確定關(guān)閉嗎?', '溫馨提示',JOptionPane.YES_NO_OPTION);if (a == 1) { server.closeServer(); System.exit(0); // 關(guān)閉} }});//底部啟動(dòng)服務(wù)按鈕與發(fā)送消息按鈕JPanel top = new JPanel(new FlowLayout());top.add(tfSend);top.add(btSend);top.add(btStart);this.add(top, BorderLayout.SOUTH);//中部顯示消息欄 信息展示final JScrollPane sp = new JScrollPane();sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);sp.setViewportView(this.taShow);this.taShow.setEditable(false);this.add(sp, BorderLayout.CENTER);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(400, 300);this.setLocation(100, 200);this.setVisible(true); } }
客戶端代碼:
package socket.clinet; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket; /** * @author 超 * Create by fengc on 2018/7/25 21:41 */public class Client extends Thread { ClientUI ui; Socket client; BufferedReader reader; PrintWriter writer; public Client(ClientUI ui) {this.ui = ui;try { String ip = ui.tfIP.getText(); //得到輸入的ip地址 int port = Integer.parseInt(ui.tfPort.getText()); //得到輸入的端口 client = new Socket(ip, port);//這里設(shè)置連接服務(wù)器端的IP的端口 println('連接服務(wù)器成功,服務(wù)器端口地址:' + port); reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer = new PrintWriter(client.getOutputStream(), true); String name = ui.tfName.getText(); if (name == null || ''.equals(name)) {name = '匿名者'; } sendMsg('會(huì)員 ' + name + ',登錄上來(lái)了........................'); // 如果為 true,則 println、printf 或 format 方法將刷新輸出緩沖區(qū)} catch (NumberFormatException nu) { println('端口請(qǐng)輸入正確.......'); nu.printStackTrace();} catch (IOException e) { println('連接服務(wù)器失?。赫?qǐng)輸入正確的IP地址與端口'); println(e.toString()); e.printStackTrace();}this.start(); } public void run() {String msg = '';while (true) { try {msg = reader.readLine(); } catch (IOException e) {println('服務(wù)器斷開(kāi)連接'); break; } if (msg != null && msg.trim() != '') {println(msg); }} } public void sendMsg(String msg) {try { writer.println(msg);} catch (Exception e) { println(e.toString());} } public void println(String s) {if (s != null) { this.ui.taShow.setText(this.ui.taShow.getText() + s + 'n'); System.out.println(s + 'n');} } }
package socket.clinet; import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent; /** * @author 超 * Create by fengc on 2018/7/25 21:40 */public class ClientUI extends JFrame { public static void main(String[] args) {new ClientUI(); } public JButton btStart; public JButton btSend; public JTextField tfSend; //裝在輸入文字 public JTextPane nameText; //輸入名字 public JTextPane ipTex; //輸入名字 public JTextPane portText; //輸入名字 public JTextField tfName; //服務(wù)器ip public JTextField tfIP; //服務(wù)器ip public JTextField tfPort; //服務(wù)器端口 public JTextArea taShow; public Client server; public ClientUI() {super('客戶端');btStart = new JButton('啟動(dòng)連接');btSend = new JButton('發(fā)送信息');tfSend = new JTextField(20);tfIP = new JTextField(8);tfPort = new JTextField(3);tfName = new JTextField(6);nameText = new JTextPane();nameText.setText('登錄名');nameText.setEditable(false);ipTex = new JTextPane();ipTex.setText('服務(wù)地址');ipTex.setEditable(false);portText = new JTextPane();portText.setText('服務(wù)端口');portText.setEditable(false);taShow = new JTextArea();//啟動(dòng)鏈接按鈕事件btStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {server = new Client(ClientUI.this); }});//發(fā)送按鈕事件btSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {String name = tfName.getText();if (name == null || ''.equals(name)) { name = '匿名者';}server.sendMsg(name + ':' + tfSend.getText());tfSend.setText(''); }}); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {int a = JOptionPane.showConfirmDialog(null, '確定關(guān)閉嗎?', '溫馨提示',JOptionPane.YES_NO_OPTION);if (a == 1) { System.exit(0); // 關(guān)閉} }});//底部的發(fā)送信息框與鏈接按鈕JPanel top = new JPanel(new FlowLayout());top.add(tfSend); //發(fā)送文本top.add(btSend); //發(fā)送按鈕this.add(top, BorderLayout.SOUTH); //加載到底部 //頭部放連接服務(wù)的JPanel northJpannel = new JPanel(new FlowLayout());northJpannel.add(nameText);northJpannel.add(tfName);northJpannel.add(ipTex);northJpannel.add(tfIP);northJpannel.add(portText);northJpannel.add(tfPort);northJpannel.add(btStart);this.add(northJpannel,BorderLayout.NORTH); //加載到頭部 final JScrollPane sp = new JScrollPane();sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);sp.setViewportView(this.taShow);this.taShow.setEditable(false);this.add(sp, BorderLayout.CENTER);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(500, 400);this.setLocation(600, 200);this.setVisible(true); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python math模塊的基本使用教程2. 如何用python開(kāi)發(fā)Zeroc Ice應(yīng)用3. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式4. python基于opencv批量生成驗(yàn)證碼的示例5. npm下載慢或下載失敗問(wèn)題解決的三種方法6. ASP編碼必備的8條原則7. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法8. python用pyecharts實(shí)現(xiàn)地圖數(shù)據(jù)可視化9. python軟件測(cè)試Jmeter性能測(cè)試JDBC Request(結(jié)合數(shù)據(jù)庫(kù))的使用詳解10. python uuid生成唯一id或str的最簡(jiǎn)單案例
