Java聊天室之實(shí)現(xiàn)使用Socket傳遞音頻
一、題目描述
題目實(shí)現(xiàn):使用網(wǎng)絡(luò)編程時,需要通過Socket傳遞音頻文件。
二、解題思路
創(chuàng)建一個服務(wù)器類:ServerSocketFrame,繼承JFrame類
寫一個getserver() 方法,實(shí)例化Socket對象,啟用9527當(dāng)服務(wù)的端口。
創(chuàng)建輸入流對象,用來接收客戶端信息。
再定義一個getClientInfo()方法,用于接收客戶端發(fā)送的音頻文件。
創(chuàng)建一個客戶端類:ClientSocketFrame,繼承JFrame類。
寫一個connect() 方法,實(shí)例化Socket對象,連接本地服務(wù)的9527端口服務(wù)。
再定義一個getClientInfo()方法,用于接收服務(wù)端發(fā)送的音頻文件。
技術(shù)重點(diǎn):
DataInputStream類的read()方法和DataOutputStream類從DataOutput類繼承的write()方法實(shí)現(xiàn)了對音頻文件的讀寫操作,與上一題不同的是,本題使用“保存”對話框,將接收到的音頻文件保存到接收方的主機(jī)上。
三、代碼詳解
ServerSocketFrame
package com.xiaoxuzhu; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; /** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre> * 修改記錄: * 修改后版本 修改人 修改日期 修改內(nèi)容 * 2022/6/5.1 xiaoxuzhu 2022/6/5 Create * </pre> * @date 2022/6/5 */ public class ServerSocketFrame extends JFrame { private JTextArea ta_info; private File file = null;// 聲明所選擇圖片的File對象 private JTextField tf_path; private DataOutputStream out = null; // 創(chuàng)建流對象 private DataInputStream in = null; // 創(chuàng)建流對象 private ServerSocket server; // 聲明ServerSocket對象 private Socket socket; // 聲明Socket對象socket private long lengths = -1; // 圖片文件的大小 private String fileName = null; public void getServer() { try { server = new ServerSocket(9527); // 實(shí)例化Socket對象 ta_info.append("服務(wù)器套接字已經(jīng)創(chuàng)建成功\n"); // 輸出信息 ta_info.append("等待客戶機(jī)的連接......\n"); // 輸出信息 socket = server.accept(); // 實(shí)例化Socket對象 ta_info.append("客戶機(jī)連接成功......\n"); // 輸出信息 while (true) { // 如果套接字是連接狀態(tài) if (socket != null && !socket.isClosed()) { out = new DataOutputStream(socket.getOutputStream());// 獲得輸出流對象 in = new DataInputStream(socket.getInputStream());// 獲得輸入流對象 getClientInfo(); // 調(diào)用getClientInfo()方法 } else { socket = server.accept(); // 實(shí)例化Socket對象 } } } catch (Exception e) { e.printStackTrace(); // 輸出異常信息 } } private void getClientInfo() { try { String name = in.readUTF();// 讀取文件名 long lengths = in.readLong();// 讀取文件的長度 byte[] bt = new byte[(int) lengths];// 創(chuàng)建字節(jié)數(shù)組 for (int i = 0; i < bt.length; i++) { bt[i] = in.readByte();// 讀取字節(jié)信息并存儲到字節(jié)數(shù)組 } FileDialog dialog = new FileDialog(ServerSocketFrame.this, "保存");// 創(chuàng)建對話框 dialog.setMode(FileDialog.SAVE);// 設(shè)置對話框?yàn)楸4鎸υ捒? dialog.setFile(name); dialog.setVisible(true);// 顯示保存對話框 String path = dialog.getDirectory();// 獲得文件的保存路徑 String newFileName = dialog.getFile();// 獲得保存的文件名 if (path == null || newFileName == null) { return; } String pathAndName = path + "\\" + newFileName;// 文件的完整路徑 FileOutputStream fOut = new FileOutputStream(pathAndName); fOut.write(bt); fOut.flush(); fOut.close(); ta_info.append("文件接收完畢。\n"); } catch (Exception e) { } finally { try { if (in != null) { in.close();// 關(guān)閉流 } if (socket != null) { socket.close(); // 關(guān)閉套接字 } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { // 主方法 ServerSocketFrame frame = new ServerSocketFrame(); // 創(chuàng)建本類對象 frame.setVisible(true); frame.getServer(); // 調(diào)用方法 } public ServerSocketFrame() { super(); setTitle("服務(wù)器端程序"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 379, 260); final JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.NORTH); final JLabel label = new JLabel(); label.setText("路徑:"); panel.add(label); tf_path = new JTextField(); tf_path.setPreferredSize(new Dimension(140, 25)); panel.add(tf_path); final JButton button_1 = new JButton(); button_1.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { JFileChooser fileChooser = new JFileChooser();// 創(chuàng)建文件選擇器 FileFilter filter = new FileNameExtensionFilter( "音頻文件(WAV/MIDI/MP3/AU)", "WAV", "MID", "MP3", "AU");// 創(chuàng)建過濾器 fileChooser.setFileFilter(filter);// 設(shè)置過濾器 int flag = fileChooser.showOpenDialog(null);// 顯示打開對話框 if (flag == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); // 獲取選中音頻文件的File對象 } if (file != null) { tf_path.setText(file.getAbsolutePath());// 音頻文件的完整路徑 fileName = file.getName();// 獲得音頻文件的名稱 } } }); button_1.setText("選擇音頻"); panel.add(button_1); final JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { DataInputStream inStream = null;// 定義數(shù)據(jù)輸入流對象 if (file != null) { lengths = file.length();// 獲得所選擇音頻文件的大小 inStream = new DataInputStream( new FileInputStream(file));// 創(chuàng)建輸入流對象 } else { JOptionPane.showMessageDialog(null, "還沒有選擇音頻文件。"); return; } out.writeUTF(fileName);// 寫入音頻文件名 out.writeLong(lengths);// 將文件的大小寫入輸出流 byte[] bt = new byte[(int) lengths];// 創(chuàng)建字節(jié)數(shù)組 int len = -1; while ((len = inStream.read(bt)) != -1) {// 將音頻文件讀取到字節(jié)數(shù)組 out.write(bt);// 將字節(jié)數(shù)組寫入輸出流 } out.flush(); out.close(); ta_info.append("文件發(fā)送完畢。\n"); } catch (IOException e1) { e1.printStackTrace(); } } }); button.setText("發(fā) 送"); panel.add(button); final JScrollPane scrollPane = new JScrollPane(); getContentPane().add(scrollPane, BorderLayout.CENTER); ta_info = new JTextArea(); scrollPane.setViewportView(ta_info); } }
ClientSocketFrame
package com.xiaoxuzhu; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; /** * Description: * * @author xiaoxuzhu * @version 1.0 * * <pre> * 修改記錄: * 修改后版本 修改人 修改日期 修改內(nèi)容 * 2022/6/5.1 xiaoxuzhu 2022/6/5 Create * </pre> * @date 2022/6/5 */ public class ClientSocketFrame extends JFrame { private JTextArea ta_info; private File file = null;// 聲明所選擇圖片的File對象 private JTextField tf_path; private DataInputStream in = null; // 創(chuàng)建流對象 private DataOutputStream out = null; // 創(chuàng)建流對象 private Socket socket; // 聲明Socket對象 private long lengths = -1;// 圖片文件的大小 private String fileName = null; private void connect() { // 連接套接字方法 ta_info.append("嘗試連接......\n"); // 文本域中信息信息 try { // 捕捉異常 socket = new Socket("127.0.0.1", 9527); // 實(shí)例化Socket對象 ta_info.append("完成連接。\n"); // 文本域中提示信息 while (true) { if (socket != null && !socket.isClosed()) { out = new DataOutputStream(socket.getOutputStream());// 獲得輸出流對象 in = new DataInputStream(socket.getInputStream());// 獲得輸入流對象 getServerInfo();// 調(diào)用getServerInfo()方法 } else { socket = new Socket("127.0.0.1", 9527); // 實(shí)例化Socket對象 } } } catch (Exception e) { e.printStackTrace(); // 輸出異常信息 } } public static void main(String[] args) { // 主方法 ClientSocketFrame clien = new ClientSocketFrame(); // 創(chuàng)建本例對象 clien.setVisible(true); // 將窗體顯示 clien.connect(); // 調(diào)用連接方法 } private void getServerInfo() { try { String name = in.readUTF();// 讀取文件名 long lengths = in.readLong();// 讀取文件的長度 byte[] bt = new byte[(int) lengths];// 創(chuàng)建字節(jié)數(shù)組 for (int i = 0; i < bt.length; i++) { bt[i] = in.readByte();// 讀取字節(jié)信息并存儲到字節(jié)數(shù)組 } FileDialog dialog = new FileDialog(ClientSocketFrame.this, "保存");// 創(chuàng)建對話框 dialog.setMode(FileDialog.SAVE);// 設(shè)置對話框?yàn)楸4鎸υ捒? dialog.setFile(name); dialog.setVisible(true);// 顯示保存對話框 String path = dialog.getDirectory();// 獲得文件的保存路徑 String newFileName = dialog.getFile();// 獲得保存的文件名 if (path == null || newFileName == null) { return; } String pathAndName = path + "\\" + newFileName;// 文件的完整路徑 FileOutputStream fOut = new FileOutputStream(pathAndName); fOut.write(bt); fOut.flush(); fOut.close(); ta_info.append("文件接收完畢。\n"); } catch (Exception e) { } finally { try { if (in != null) { in.close();// 關(guān)閉流 } if (socket != null) { socket.close(); // 關(guān)閉套接字 } } catch (IOException e) { e.printStackTrace(); } } } /** * Create the frame */ public ClientSocketFrame() { super(); setTitle("客戶端程序"); setBounds(100, 100, 373, 257); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.NORTH); final JLabel label = new JLabel(); label.setText("路徑:"); panel.add(label); tf_path = new JTextField(); tf_path.setPreferredSize(new Dimension(140,25)); panel.add(tf_path); final JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { JFileChooser fileChooser = new JFileChooser();// 創(chuàng)建文件選擇器 FileFilter filter = new FileNameExtensionFilter("音頻文件(WAV/MIDI/MP3/AU)", "WAV", "MID", "MP3", "AU");// 創(chuàng)建過濾器 fileChooser.setFileFilter(filter);// 設(shè)置過濾器 int flag = fileChooser.showOpenDialog(null);// 顯示打開對話框 if (flag == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); // 獲取選中音頻文件的File對象 } if (file != null) { tf_path.setText(file.getAbsolutePath());// 音頻文件的完整路徑 fileName = file.getName();// 獲得音頻文件的名稱 } } }); button.setText("選擇音頻"); panel.add(button); final JButton button_1 = new JButton(); button_1.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { DataInputStream inStream = null;// 定義數(shù)據(jù)輸入流對象 if (file != null) { lengths = file.length();// 獲得所選擇音頻文件的大小 inStream = new DataInputStream(new FileInputStream(file));// 創(chuàng)建輸入流對象 } else { JOptionPane.showMessageDialog(null, "還沒有選擇音頻文件。"); return; } out.writeUTF(fileName);// 寫入音頻文件名 out.writeLong(lengths);// 將文件的大小寫入輸出流 byte[] bt = new byte[(int) lengths];// 創(chuàng)建字節(jié)數(shù)組 int len = -1;// 用于存儲讀取到的字節(jié)數(shù) while ((len = inStream.read(bt)) != -1) {// 將音頻文件讀取到字節(jié)數(shù)組 out.write(bt);// 將字節(jié)數(shù)組寫入輸出流 } out.flush();// 更新輸出流對象 out.close();// 關(guān)閉輸出流對象 ta_info.append("文件發(fā)送完畢。\n"); } catch (IOException e1) { e1.printStackTrace(); } } }); button_1.setText("發(fā) 送"); panel.add(button_1); final JScrollPane scrollPane = new JScrollPane(); getContentPane().add(scrollPane, BorderLayout.CENTER); ta_info = new JTextArea(); scrollPane.setViewportView(ta_info); // } }
服務(wù)器啟動
客戶端啟動
客戶端向服務(wù)端發(fā)送音頻
服務(wù)端接收到音頻,選擇保存位置
提示接收完成
服務(wù)端向客戶端發(fā)送音頻,客戶端接收到音頻
多學(xué)一個知識點(diǎn)
傳輸視頻的原理跟傳遞音頻的原理是一樣的,差別是上面代碼打開的文件選擇對話框中,顯示文件類型是視頻格式的文件,這樣可以方便用戶對視頻文件進(jìn)行選擇。
以上就是Java聊天室之實(shí)現(xiàn)使用Socket傳遞音頻的詳細(xì)內(nèi)容,更多關(guān)于Java聊天室的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java中Spock框架Mock對象的方法經(jīng)驗(yàn)總結(jié)
這篇文章主要分享了Spock框架Mock對象的方法經(jīng)驗(yàn)總結(jié),下文分享一些常用項(xiàng)目實(shí)戰(zhàn)說明以及代碼,供大家項(xiàng)目中參考,也具有一的的參考價值,需要的小伙伴可以參考一下2022-02-02Spring?boot?Thymeleaf配置國際化頁面詳解
這篇文章主要給大家介紹了關(guān)于Spring?Boot?Thymeleaf實(shí)現(xiàn)國際化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring?Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07MybatisPlus,無XML分分鐘實(shí)現(xiàn)CRUD操作
這篇文章主要介紹了MybatisPlus,無XML分分鐘實(shí)現(xiàn)CRUD操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08詳解SpringBoot的三種緩存技術(shù)(Spring Cache、Layering Cache 框架、Alibaba J
這篇文章主要介紹了SpringBoot的三種緩存技術(shù),幫助大家更好的理解和學(xué)習(xí)springboot框架,感興趣的朋友可以了解下2020-10-10Java深入了解數(shù)據(jù)結(jié)構(gòu)之棧與隊列的詳解
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)中的棧與隊列,在Java的時候,對于棧與隊列的應(yīng)用需要熟練的掌握,這樣才能夠確保Java學(xué)習(xí)時候能夠有扎實(shí)的基礎(chǔ)能力。本文小編就來詳細(xì)說說Java中的棧與隊列,需要的朋友可以參考一下2022-01-01關(guān)于spring.factories失效原因分析及解決
這篇文章主要介紹了關(guān)于spring.factories失效原因分析及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07SpringBoot整合MyBatis四種常用的分頁方式(詳細(xì)總結(jié))
這篇文章詳細(xì)給大家總結(jié)了SpringBoot整合MyBatis四種常用的分頁方式,文中通過代碼示例為大家介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07