回城传送–》《JAVA筑基100例》
零、前言
? 今天是学习 JAVA语言 打卡的第95天,每天我会提供一篇文章供群成员阅读( 不需要订阅付钱 ),读完文章之后,按解题思路,自己再实现一遍。在小虚竹JAVA社区 中对应的 【打卡贴】打卡,今天的任务就算完成了。
? 因为大家都在一起学习同一篇文章,所以有什么问题都可以在群里问,群里的小伙伴可以迅速地帮到你,一个人可以走得很快,一群人可以走得很远,有一起学习交流的战友,是多么幸运的事情。
? 学完后,自己写篇学习报告的博客,可以发布到小虚竹JAVA社区 ,供学弟学妹们参考。
? 我的学习策略很简单,题海策略+ 费曼学习法。如果能把这100题都认认真真自己实现一遍,那意味着 JAVA语言 已经筑基成功了。后面的进阶学习,可以继续跟着我,一起走向架构师之路。
一、题目描述
题目实现:使用网络编程时,需要通过Socket传递音频文件。
二、解题思路
创建一个服务器类:ServerSocketFrame,继承JFrame类
写一个getserver() 方法,实例化Socket对象,启用9527当服务的端口。
创建输入流对象,用来接收客户端信息。
再定义一个getClientInfo()方法,用于接收客户端发送的音频文件。
创建一个客户端类:ClientSocketFrame,继承JFrame类。
写一个connect() 方法,实例化Socket对象,连接本地服务的9527端口服务。
再定义一个getClientInfo()方法,用于接收服务端发送的音频文件。
技术重点:
DataInputStream类的read()方法和DataOutputStream类从DataOutput类继承的write()方法实现了对音频文件的读写操作,与上一题不同的是,本题使用“保存”对话框,将接收到的音频文件保存到接收方的主机上。
三、代码详解
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;
public class ServerSocketFrame extends JFrame {
private JTextArea ta_info;
private File file = null;
private JTextField tf_path;
private DataOutputStream out = null;
private DataInputStream in = null;
private ServerSocket server;
private Socket socket;
private long lengths = -1;
private String fileName = null;
public void getServer() {
try {
server = new ServerSocket(9527);
ta_info.append("服务器套接字已经创建成功\n");
ta_info.append("等待客户机的连接......\n");
socket = server.accept();
ta_info.append("客户机连接成功......\n");
while (true) {
if (socket != null && !socket.isClosed()) {
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
getClientInfo();
} else {
socket = server.accept();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getClientInfo() {
try {
String name = in.readUTF();
long lengths = in.readLong();
byte[] bt = new byte[(int) lengths];
for (int i = 0; i < bt.length; i++) {
bt[i] = in.readByte();
}
FileDialog dialog = new FileDialog(ServerSocketFrame.this, "保存");
dialog.setMode(FileDialog.SAVE);
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();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ServerSocketFrame frame = new ServerSocketFrame();
frame.setVisible(true);
frame.getServer();
}
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();
FileFilter filter = new FileNameExtensionFilter(
"音频文件(WAV/MIDI/MP3/AU)", "WAV", "MID", "MP3", "AU");
fileChooser.setFileFilter(filter);
int flag = fileChooser.showOpenDialog(null);
if (flag == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
}
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;
if (file != null) {
lengths = file.length();
inStream = new DataInputStream(
new FileInputStream(file));
} else {
JOptionPane.showMessageDialog(null, "还没有选择音频文件。");
return;
}
out.writeUTF(fileName);
out.writeLong(lengths);
byte[] bt = new byte[(int) lengths];
int len = -1;
while ((len = inStream.read(bt)) != -1) {
out.write(bt);
}
out.flush();
out.close();
ta_info.append("文件发送完毕。\n");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setText("发 送");
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;
public class ClientSocketFrame extends JFrame {
private JTextArea ta_info;
private File file = null;
private JTextField tf_path;
private DataInputStream in = null;
private DataOutputStream out = null;
private 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);
ta_info.append("完成连接。\n");
while (true) {
if (socket != null && !socket.isClosed()) {
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
getServerInfo();
} else {
socket = new Socket("127.0.0.1", 9527);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ClientSocketFrame clien = new ClientSocketFrame();
clien.setVisible(true);
clien.connect();
}
private void getServerInfo() {
try {
String name = in.readUTF();
long lengths = in.readLong();
byte[] bt = new byte[(int) lengths];
for (int i = 0; i < bt.length; i++) {
bt[i] = in.readByte();
}
FileDialog dialog = new FileDialog(ClientSocketFrame.this, "保存");
dialog.setMode(FileDialog.SAVE);
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();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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();
FileFilter filter = new FileNameExtensionFilter("音频文件(WAV/MIDI/MP3/AU)", "WAV", "MID", "MP3", "AU");
fileChooser.setFileFilter(filter);
int flag = fileChooser.showOpenDialog(null);
if (flag == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
}
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;
if (file != null) {
lengths = file.length();
inStream = new DataInputStream(new FileInputStream(file));
} else {
JOptionPane.showMessageDialog(null, "还没有选择音频文件。");
return;
}
out.writeUTF(fileName);
out.writeLong(lengths);
byte[] bt = new byte[(int) lengths];
int len = -1;
while ((len = inStream.read(bt)) != -1) {
out.write(bt);
}
out.flush();
out.close();
ta_info.append("文件发送完毕。\n");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button_1.setText("发 送");
panel.add(button_1);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
ta_info = new JTextArea();
scrollPane.setViewportView(ta_info);
}
}
服务器启动
客户端启动
客户端向服务端发送音频
服务端接收到音频,选择保存位置
提示接收完成
服务端向客户端发送音频,客户端接收到音频
多学一个知识点
传输视频的原理跟传递音频的原理是一样的,差别是上面代码打开的文件选择对话框中,显示文件类型是视频格式的文件,这样可以方便用户对视频文件进行选择。
四、推荐专栏
《JAVA从零到壹》
《JAVA筑基100例》
五、示例源码下载
关注下面的公众号,回复筑基+题目号
筑基95
|