這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)使用java怎么實(shí)現(xiàn)一個(gè)局域網(wǎng)聊天小程序,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)2013年開創(chuàng)至今,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站建設(shè)、網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元蘭西做網(wǎng)站,已為上家服務(wù),為蘭西各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:13518219792
Client.java 客戶端代碼
package chat; import java.awt.BorderLayout;//布置容器的邊框布局 import java.awt.Color; import java.awt.Container; import java.awt.GridLayout;//布局處理器 import java.awt.Toolkit;//抽象超類 import java.awt.event.ActionEvent;//指示發(fā)生了組件定義的動(dòng)作的語義事件 import java.awt.event.ActionListener;//用于接收操作事件的偵聽器接口 import java.awt.event.MouseEvent;//指示組件中發(fā)生鼠標(biāo)動(dòng)作的事件 import java.awt.event.MouseListener;//鼠標(biāo)事件的偵聽器接口 import java.awt.event.WindowAdapter;//接收窗口事件的抽象適配器類。此類中的方法為空。此類存在的目的是方便創(chuàng)建偵聽器對(duì)象 import java.awt.event.WindowEvent;//指示窗口狀態(tài)改變的低級(jí)別事件 import java.io.BufferedReader;//提供通用的緩沖方式文本讀取 import java.io.IOException;//輸入輸出異常 import java.io.InputStreamReader;//字節(jié)流通向字符流的橋梁 import java.io.PrintWriter;//向文本輸出流打印對(duì)象的格式化表示形式 import java.net.Socket;//套接字,網(wǎng)絡(luò)上的兩個(gè)程序通過一個(gè)雙向的通信連接實(shí)現(xiàn)數(shù)據(jù)交換的通信 import java.util.HashMap;// HashMap 是 Map 接口的常用實(shí)現(xiàn)類 import java.util.Map;//存數(shù)據(jù),將鍵映射到值的對(duì)象 import java.util.StringTokenizer;//允許應(yīng)用程序?qū)⒆址纸鉃闃?biāo)記 import javax.swing.BorderFactory;//創(chuàng)建一個(gè)浮雕式的邊框 import javax.swing.DefaultListModel;//列表模型 import javax.swing.JButton;//按鈕 import javax.swing.JFrame;//窗口 import javax.swing.JLabel;//標(biāo)簽 import javax.swing.JList;//列表 import javax.swing.JOptionPane;//對(duì)話框 import javax.swing.JPanel; import javax.swing.JScrollPane;//視圖 import javax.swing.JSplitPane;//分隔 import javax.swing.JTextArea;//多行文本 import javax.swing.JTextField;//文本 import javax.swing.border.EmptyBorder;//一個(gè)占用空間但不執(zhí)行繪制的空透明邊框 import javax.swing.border.TitledBorder;//該類實(shí)現(xiàn)在指定位置以指定對(duì)齊方式顯示字符串標(biāo)題的任意邊框 import oldchat.ChatFrame; public class Client { private JFrame frame; private JList userList; private JTextArea textArea; private JTextField textField; private JTextField txt_port; private JTextField txt_hostIp; private JTextField txt_name; private JButton btn_start; private JButton btn_stop; private JButton btn_send; private JPanel northPanel; private JPanel southPanel; private JScrollPane rightScroll; private JScrollPane leftScroll; private JSplitPane centerSplit; private DefaultListModel listModel; private boolean isConnected = false; private Socket socket;//創(chuàng)建套接字 private PrintWriter writer; private BufferedReader reader; private MessageThread messageThread;// 負(fù)責(zé)接收消息的線程 private Map<String, User> onLineUsers = new HashMap<String, User>();// 所有在線用戶 // 主方法,程序入口 public static void main(String[] args) { new Client(); } // 執(zhí)行發(fā)送 public void send() { if (!isConnected) { JOptionPane.showMessageDialog(frame, "還沒有連接服務(wù)器,無法發(fā)送消息!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } String message = textField.getText().trim(); if (message == null || message.equals("")) { JOptionPane.showMessageDialog(frame, "消息不能為空!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } sendMessage(frame.getTitle() + "@" + "ALL" + "@" + message); textField.setText(null); } // 構(gòu)造方法 public Client() { textArea = new JTextArea(); textArea.setEditable(false); textArea.setForeground(Color.blue); textField = new JTextField(); txt_port = new JTextField("6666"); txt_hostIp = new JTextField(); txt_name = new JTextField(); btn_start = new JButton("連接"); btn_stop = new JButton("斷開"); btn_send = new JButton("發(fā)送"); listModel = new DefaultListModel(); userList = new JList(listModel); northPanel = new JPanel(); northPanel.setLayout(new GridLayout(1, 7)); northPanel.add(new JLabel("端口")); northPanel.add(txt_port); northPanel.add(new JLabel("服務(wù)器IP")); northPanel.add(txt_hostIp); northPanel.add(new JLabel("姓名")); northPanel.add(txt_name); northPanel.add(btn_start); northPanel.add(btn_stop); northPanel.setBorder(new TitledBorder("連接信息")); rightScroll = new JScrollPane(textArea); rightScroll.setBorder(new TitledBorder("群聊消息顯示區(qū)")); leftScroll = new JScrollPane(userList); leftScroll.setBorder(new TitledBorder("在線用戶(雙擊私聊)")); southPanel = new JPanel(new BorderLayout()); southPanel.add(textField, "Center"); southPanel.add(btn_send, "East"); southPanel.setBorder(new TitledBorder("寫消息")); centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScroll, rightScroll); centerSplit.setDividerLocation(100); frame = new JFrame("客戶端"); // 更改JFrame的圖標(biāo): //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.jpg"))); frame.setLayout(new BorderLayout()); frame.add(northPanel, "North"); frame.add(centerSplit, "Center"); frame.add(southPanel, "South"); frame.setSize(600, 400); int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width; int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height; frame.setLocation((screen_width - frame.getWidth()) / 2, (screen_height - frame.getHeight()) / 2); frame.setVisible(true); // 寫消息的文本框中按回車鍵時(shí)事件 textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { send(); } }); // 單擊發(fā)送按鈕時(shí)事件 btn_send.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { send(); } }); // 單擊連接按鈕時(shí)事件 btn_start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int port; if (isConnected) { JOptionPane.showMessageDialog(frame, "已處于連接上狀態(tài),不要重復(fù)連接!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } try { try { port = Integer.parseInt(txt_port.getText().trim()); } catch (NumberFormatException e2) { throw new Exception("端口號(hào)不符合要求!端口為整數(shù)!"); } String hostIp = txt_hostIp.getText().trim(); String name = txt_name.getText().trim(); if (name.equals("") || hostIp.equals("")) { throw new Exception("姓名、服務(wù)器IP不能為空!"); } boolean flag = connectServer(port, hostIp, name); if (flag == false) { throw new Exception("與服務(wù)器連接失敗!"); } frame.setTitle(name); JOptionPane.showMessageDialog(frame, "成功連接!"); } catch (Exception exc) { JOptionPane.showMessageDialog(frame, exc.getMessage(), "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); } } }); //雙擊聊天(私聊) userList.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) { if(e.getClickCount()==2) { User user=onLineUsers.get(userList.getSelectedValue()); ChatFrame.main(user.getIp());; } } }); // 單擊斷開按鈕時(shí)事件 btn_stop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isConnected) { JOptionPane.showMessageDialog(frame, "已處于斷開狀態(tài),不要重復(fù)斷開!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } try { boolean flag = closeConnection();// 斷開連接 if (flag == false) { throw new Exception("斷開連接發(fā)生異常!"); } JOptionPane.showMessageDialog(frame, "成功斷開!"); } catch (Exception exc) { JOptionPane.showMessageDialog(frame, exc.getMessage(), "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); } } }); // 關(guān)閉窗口時(shí)事件 frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (isConnected) { closeConnection();// 關(guān)閉連接 } System.exit(0);// 退出程序 } }); } /** * 連接服務(wù)器 * * @param port * @param hostIp * @param name */ public boolean connectServer(int port, String hostIp, String name) { // 連接服務(wù)器 try { socket = new Socket(hostIp, port);// 根據(jù)端口號(hào)和服務(wù)器ip建立連接 writer = new PrintWriter(socket.getOutputStream()); reader = new BufferedReader(new InputStreamReader(socket .getInputStream())); // 發(fā)送客戶端用戶基本信息(用戶名和ip地址) sendMessage(name + "@" + socket.getLocalAddress().toString()); // 開啟接收消息的線程 messageThread = new MessageThread(reader, textArea); messageThread.start(); isConnected = true;// 已經(jīng)連接上了 return true; } catch (Exception e) { textArea.append("與端口號(hào)為:" + port + " IP地址為:" + hostIp + " 的服務(wù)器連接失敗!" + "\r\n"); isConnected = false;// 未連接上 return false; } } /** * 發(fā)送消息 * * @param message */ public void sendMessage(String message) { writer.println(message); writer.flush(); } /** * 客戶端主動(dòng)關(guān)閉連接 */ @SuppressWarnings("deprecation") public synchronized boolean closeConnection() { try { sendMessage("CLOSE");// 發(fā)送斷開連接命令給服務(wù)器 messageThread.stop();// 停止接受消息線程 // 釋放資源 if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } if (socket != null) { socket.close(); } isConnected = false; return true; } catch (IOException e1) { e1.printStackTrace(); isConnected = true; return false; } } // 不斷接收消息的線程 class MessageThread extends Thread { private BufferedReader reader; private JTextArea textArea; // 接收消息線程的構(gòu)造方法 public MessageThread(BufferedReader reader, JTextArea textArea) { this.reader = reader; this.textArea = textArea; } // 被動(dòng)的關(guān)閉連接 public synchronized void closeCon() throws Exception { // 清空用戶列表 listModel.removeAllElements(); // 被動(dòng)的關(guān)閉連接釋放資源 if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } if (socket != null) { socket.close(); } isConnected = false;// 修改狀態(tài)為斷開 } public void run() { String message = ""; while (true) { try { message = reader.readLine(); StringTokenizer stringTokenizer = new StringTokenizer(message, "/@"); String command = stringTokenizer.nextToken();// 命令 if (command.equals("CLOSE"))// 服務(wù)器已關(guān)閉命令 { textArea.append("服務(wù)器已關(guān)閉!\r\n"); closeCon();// 被動(dòng)的關(guān)閉連接 return;// 結(jié)束線程 } else if (command.equals("ADD")) {// 有用戶上線更新在線列表 String username = ""; String userIp = ""; if ((username = stringTokenizer.nextToken()) != null && (userIp = stringTokenizer.nextToken()) != null) { User user = new User(username, userIp); onLineUsers.put(username, user); listModel.addElement(username); } } else if (command.equals("DELETE")) {// 有用戶下線更新在線列表 String username = stringTokenizer.nextToken(); User user = (User) onLineUsers.get(username); onLineUsers.remove(user); listModel.removeElement(username); } else if (command.equals("USERLIST")) {// 加載在線用戶列表 int size = Integer .parseInt(stringTokenizer.nextToken()); String username = null; String userIp = null; for (int i = 0; i < size; i++) { username = stringTokenizer.nextToken(); userIp = stringTokenizer.nextToken(); User user = new User(username, userIp); onLineUsers.put(username, user); listModel.addElement(username); } } else if (command.equals("MAX")) {// 人數(shù)已達(dá)上限 textArea.append(stringTokenizer.nextToken() + stringTokenizer.nextToken() + "\r\n"); closeCon();// 被動(dòng)的關(guān)閉連接 JOptionPane.showMessageDialog(frame, "服務(wù)器緩沖區(qū)已滿!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return;// 結(jié)束線程 } else {// 普通消息 textArea.append(message + "\r\n"); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } } }
Server.java
package chat; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.TitledBorder; public class Server { private JFrame frame; private JTextArea contentArea; private JTextField txt_message; private JTextField txt_max; private JTextField txt_port; private JButton btn_start; private JButton btn_stop; private JButton btn_send; private JPanel northPanel; private JPanel southPanel; private JScrollPane rightPanel; private JScrollPane leftPanel; private JSplitPane centerSplit; private JList userList; private DefaultListModel listModel; private ServerSocket serverSocket; private ServerThread serverThread; private ArrayList<ClientThread> clients; private boolean isStart = false; // 主方法,程序執(zhí)行入口 public static void main(String[] args) { new Server(); } // 執(zhí)行消息發(fā)送 public void send() { if (!isStart) { JOptionPane.showMessageDialog(frame, "服務(wù)器還未啟動(dòng),不能發(fā)送消息!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } if (clients.size() == 0) { JOptionPane.showMessageDialog(frame, "沒有用戶在線,不能發(fā)送消息!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } String message = txt_message.getText().trim(); if (message == null || message.equals("")) { JOptionPane.showMessageDialog(frame, "消息不能為空!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } sendServerMessage(message);// 群發(fā)服務(wù)器消息 contentArea.append("服務(wù)器說:" + txt_message.getText() + "\r\n"); txt_message.setText(null); } // 構(gòu)造放法 public Server() { frame = new JFrame("服務(wù)器"); // 更改JFrame的圖標(biāo): //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png"))); //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Server.class.getResource("qq.jpg"))); contentArea = new JTextArea(); contentArea.setEditable(false); contentArea.setForeground(Color.blue); txt_message = new JTextField(); txt_max = new JTextField("30"); txt_port = new JTextField("6666"); btn_start = new JButton("啟動(dòng)"); btn_stop = new JButton("停止"); btn_send = new JButton("發(fā)送"); btn_stop.setEnabled(false); listModel = new DefaultListModel(); userList = new JList(listModel); southPanel = new JPanel(new BorderLayout()); southPanel.setBorder(new TitledBorder("寫消息")); southPanel.add(txt_message, "Center"); southPanel.add(btn_send, "East"); leftPanel = new JScrollPane(userList); leftPanel.setBorder(new TitledBorder("在線用戶")); rightPanel = new JScrollPane(contentArea); rightPanel.setBorder(new TitledBorder("群聊消息顯示區(qū)")); centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel); centerSplit.setDividerLocation(100); northPanel = new JPanel(); northPanel.setLayout(new GridLayout(1, 6)); northPanel.add(new JLabel("人數(shù)上限")); northPanel.add(txt_max); northPanel.add(new JLabel("端口")); northPanel.add(txt_port); northPanel.add(btn_start); northPanel.add(btn_stop); northPanel.setBorder(new TitledBorder("配置信息")); frame.setLayout(new BorderLayout()); frame.add(northPanel, "North"); frame.add(centerSplit, "Center"); frame.add(southPanel, "South"); frame.setSize(600, 400); //frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());//設(shè)置全屏 int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width; int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height; frame.setLocation((screen_width - frame.getWidth()) / 2, (screen_height - frame.getHeight()) / 2); frame.setVisible(true); // 關(guān)閉窗口時(shí)事件 frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (isStart) { closeServer();// 關(guān)閉服務(wù)器 } System.exit(0);// 退出程序 } }); // 文本框按回車鍵時(shí)事件 txt_message.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { send(); } }); // 單擊發(fā)送按鈕時(shí)事件 btn_send.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { send(); } }); // 單擊啟動(dòng)服務(wù)器按鈕時(shí)事件 btn_start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isStart) { JOptionPane.showMessageDialog(frame, "服務(wù)器已處于啟動(dòng)狀態(tài),不要重復(fù)啟動(dòng)!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } int max; int port; try { try { max = Integer.parseInt(txt_max.getText()); } catch (Exception e1) { throw new Exception("人數(shù)上限為正整數(shù)!"); } if (max <= 0) { throw new Exception("人數(shù)上限為正整數(shù)!"); } try { port = Integer.parseInt(txt_port.getText()); } catch (Exception e1) { throw new Exception("端口號(hào)為正整數(shù)!"); } if (port <= 0) { throw new Exception("端口號(hào) 為正整數(shù)!"); } serverStart(max, port); contentArea.append("服務(wù)器已成功啟動(dòng)!人數(shù)上限:" + max + ",端口:" + port + "\r\n"); JOptionPane.showMessageDialog(frame, "服務(wù)器成功啟動(dòng)!"); btn_start.setEnabled(false); txt_max.setEnabled(false); txt_port.setEnabled(false); btn_stop.setEnabled(true); } catch (Exception exc) { JOptionPane.showMessageDialog(frame, exc.getMessage(), "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); } } }); // 單擊停止服務(wù)器按鈕時(shí)事件 btn_stop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isStart) { JOptionPane.showMessageDialog(frame, "服務(wù)器還未啟動(dòng),無需停止!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); return; } try { closeServer(); btn_start.setEnabled(true); txt_max.setEnabled(true); txt_port.setEnabled(true); btn_stop.setEnabled(false); contentArea.append("服務(wù)器成功停止!\r\n"); JOptionPane.showMessageDialog(frame, "服務(wù)器成功停止!"); } catch (Exception exc) { JOptionPane.showMessageDialog(frame, "停止服務(wù)器發(fā)生異常!", "錯(cuò)誤", JOptionPane.ERROR_MESSAGE); } } }); } // 啟動(dòng)服務(wù)器 public void serverStart(int max, int port) throws java.net.BindException { try { clients = new ArrayList<ClientThread>(); serverSocket = new ServerSocket(port); serverThread = new ServerThread(serverSocket, max); serverThread.start(); isStart = true; } catch (BindException e) { isStart = false; throw new BindException("端口號(hào)已被占用,請(qǐng)換一個(gè)!"); } catch (Exception e1) { e1.printStackTrace(); isStart = false; throw new BindException("啟動(dòng)服務(wù)器異常!"); } } // 關(guān)閉服務(wù)器 @SuppressWarnings("deprecation") public void closeServer() { try { if (serverThread != null) serverThread.stop();// 停止服務(wù)器線程 for (int i = clients.size() - 1; i >= 0; i--) { // 給所有在線用戶發(fā)送關(guān)閉命令 clients.get(i).getWriter().println("CLOSE"); clients.get(i).getWriter().flush(); // 釋放資源 clients.get(i).stop();// 停止此條為客戶端服務(wù)的線程 clients.get(i).reader.close(); clients.get(i).writer.close(); clients.get(i).socket.close(); clients.remove(i); } if (serverSocket != null) { serverSocket.close();// 關(guān)閉服務(wù)器端連接 } listModel.removeAllElements();// 清空用戶列表 isStart = false; } catch (IOException e) { e.printStackTrace(); isStart = true; } } // 群發(fā)服務(wù)器消息 public void sendServerMessage(String message) { for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println("服務(wù)器:" + message); clients.get(i).getWriter().flush(); } } // 服務(wù)器線程 class ServerThread extends Thread { private ServerSocket serverSocket; private int max;// 人數(shù)上限 // 服務(wù)器線程的構(gòu)造方法 public ServerThread(ServerSocket serverSocket, int max) { this.serverSocket = serverSocket; this.max = max; } public void run() { while (true) {// 不停的等待客戶端的鏈接 try { Socket socket = serverSocket.accept(); if (clients.size() == max) {// 如果已達(dá)人數(shù)上限 BufferedReader r = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter w = new PrintWriter(socket .getOutputStream()); // 接收客戶端的基本用戶信息 String inf = r.readLine(); StringTokenizer st = new StringTokenizer(inf, "@"); User user = new User(st.nextToken(), st.nextToken()); // 反饋連接成功信息 w.println("MAX@服務(wù)器:對(duì)不起," + user.getName() + user.getIp() + ",服務(wù)器在線人數(shù)已達(dá)上限,請(qǐng)稍后嘗試連接!"); w.flush(); // 釋放資源 r.close(); w.close(); socket.close(); continue; } ClientThread client = new ClientThread(socket); client.start();// 開啟對(duì)此客戶端服務(wù)的線程 clients.add(client); listModel.addElement(client.getUser().getName());// 更新在線列表 contentArea.append(client.getUser().getName() + client.getUser().getIp() + "上線!\r\n"); } catch (IOException e) { e.printStackTrace(); } } } } // 為一個(gè)客戶端服務(wù)的線程 class ClientThread extends Thread { private Socket socket; private BufferedReader reader; private PrintWriter writer; private User user; public BufferedReader getReader() { return reader; } public PrintWriter getWriter() { return writer; } public User getUser() { return user; } // 客戶端線程的構(gòu)造方法 public ClientThread(Socket socket) { try { this.socket = socket; reader = new BufferedReader(new InputStreamReader(socket .getInputStream())); writer = new PrintWriter(socket.getOutputStream()); // 接收客戶端的基本用戶信息 String inf = reader.readLine(); StringTokenizer st = new StringTokenizer(inf, "@"); user = new User(st.nextToken(), st.nextToken()); // 反饋連接成功信息 writer.println(user.getName() + user.getIp() + "與服務(wù)器連接成功!"); writer.flush(); // 反饋當(dāng)前在線用戶信息 if (clients.size() > 0) { String temp = ""; for (int i = clients.size() - 1; i >= 0; i--) { temp += (clients.get(i).getUser().getName() + "/" + clients .get(i).getUser().getIp()) + "@"; } writer.println("USERLIST@" + clients.size() + "@" + temp); writer.flush(); } // 向所有在線用戶發(fā)送該用戶上線命令 for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println( "ADD@" + user.getName() + user.getIp()); clients.get(i).getWriter().flush(); } } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("deprecation") public void run() {// 不斷接收客戶端的消息,進(jìn)行處理。 String message = null; while (true) { try { message = reader.readLine();// 接收客戶端消息 if (message.equals("CLOSE"))// 下線命令 { contentArea.append(this.getUser().getName() + this.getUser().getIp() + "下線!\r\n"); // 斷開連接釋放資源 reader.close(); writer.close(); socket.close(); // 向所有在線用戶發(fā)送該用戶的下線命令 for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println( "DELETE@" + user.getName()); clients.get(i).getWriter().flush(); } listModel.removeElement(user.getName());// 更新在線列表 // 刪除此條客戶端服務(wù)線程 for (int i = clients.size() - 1; i >= 0; i--) { if (clients.get(i).getUser() == user) { ClientThread temp = clients.get(i); clients.remove(i);// 刪除此用戶的服務(wù)線程 temp.stop();// 停止這條服務(wù)線程 return; } } } else { dispatcherMessage(message);// 轉(zhuǎn)發(fā)消息 } } catch (IOException e) { e.printStackTrace(); } } } // 轉(zhuǎn)發(fā)消息 public void dispatcherMessage(String message) { StringTokenizer stringTokenizer = new StringTokenizer(message, "@"); String source = stringTokenizer.nextToken(); String owner = stringTokenizer.nextToken(); String content = stringTokenizer.nextToken(); message = source + "說:" + content; contentArea.append(message + "\r\n"); if (owner.equals("ALL")) {// 群發(fā) for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println(message); clients.get(i).getWriter().flush(); } } } } }
運(yùn)行截圖
上述就是小編為大家分享的使用java怎么實(shí)現(xiàn)一個(gè)局域網(wǎng)聊天小程序了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
本文標(biāo)題:使用java怎么實(shí)現(xiàn)一個(gè)局域網(wǎng)聊天小程序
轉(zhuǎn)載源于:http://m.newbst.com/article6/jeiiog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、企業(yè)建站、網(wǎng)站建設(shè)、虛擬主機(jī)、做網(wǎng)站、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)