Java聊天室之實現(xiàn)使用Socket傳遞音頻
一、題目描述
題目實現(xiàn):使用網(wǎng)絡(luò)編程時,需要通過Socket傳遞音頻文件。
二、解題思路
創(chuàng)建一個服務器類:ServerSocketFrame,繼承JFrame類
寫一個getserver() 方法,實例化Socket對象,啟用9527當服務的端口。
創(chuàng)建輸入流對象,用來接收客戶端信息。
再定義一個getClientInfo()方法,用于接收客戶端發(fā)送的音頻文件。
創(chuàng)建一個客戶端類:ClientSocketFrame,繼承JFrame類。
寫一個connect() 方法,實例化Socket對象,連接本地服務的9527端口服務。
再定義一個getClientInfo()方法,用于接收服務端發(fā)送的音頻文件。
技術(shù)重點:
DataInputStream類的read()方法和DataOutputStream類從DataOutput類繼承的write()方法實現(xiàn)了對音頻文件的讀寫操作,與上一題不同的是,本題使用“保存”對話框,將接收到的音頻文件保存到接收方的主機上。
三、代碼詳解
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); // 實例化Socket對象
ta_info.append("服務器套接字已經(jīng)創(chuàng)建成功\n"); // 輸出信息
ta_info.append("等待客戶機的連接......\n"); // 輸出信息
socket = server.accept(); // 實例化Socket對象
ta_info.append("客戶機連接成功......\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(); // 實例化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è)置對話框為保存對話框
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("服務器端程序");
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); // 實例化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); // 實例化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è)置對話框為保存對話框
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);
//
}
}
服務器啟動

客戶端啟動

客戶端向服務端發(fā)送音頻

服務端接收到音頻,選擇保存位置

提示接收完成

服務端向客戶端發(fā)送音頻,客戶端接收到音頻


多學一個知識點
傳輸視頻的原理跟傳遞音頻的原理是一樣的,差別是上面代碼打開的文件選擇對話框中,顯示文件類型是視頻格式的文件,這樣可以方便用戶對視頻文件進行選擇。
以上就是Java聊天室之實現(xiàn)使用Socket傳遞音頻的詳細內(nèi)容,更多關(guān)于Java聊天室的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決 IDEA 創(chuàng)建 Gradle 項目沒有src目錄問題
這篇文章主要介紹了解決 IDEA 創(chuàng)建 Gradle 項目沒有src目錄問題,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
SpringMvc/SpringBoot HTTP通信加解密的實現(xiàn)
這篇文章主要介紹了SpringMvc/SpringBoot HTTP通信加解密的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08
Spring Security中的Servlet過濾器體系代碼分析
這篇文章主要介紹了Spring Security中的Servlet過濾器體系,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
SpringBoot中的ApplicationRunner與CommandLineRunner問題
這篇文章主要介紹了SpringBoot中的ApplicationRunner與CommandLineRunner問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

