基于JAVA的网络编程——socket文件传输
文章目录
效果图
功能实现
- 使用多线程技术来提高程序的执行效率
- 采用选择文件的方式来实现文件选择的可视化操作
- 采用时间戳+名称+扩展名的方式实现同一文件,传输不可覆盖操作
- 采用传输文件扩展名的方式实现任意类型的文件传输过程中不改变文件类型
步骤
客户端实现步骤:
- 创建一个本地字节输入流FileInputStream对象,构造方法中绑定要读取的数据源
- 创建- -个客户端Socket对象 ,构造方法中绑定服务器的IP地址和端口号
- 使用Socket中的方法getOutputStream,获取网络字节输出流0utputStream对象
- 使用本地字节输入流FileInputstream对象中的方法read,读取本地文件
- 使用网络字节输出流OutputStream对象中的方法write ,把读取到的文件.上传到服务器
- 使用Socket中的方法getInputStream,获取网络字节输入流InputStream对象
- 使用网络字节输入流InputStream对象中的方法read读取服务回写的数据
- 释放资源(FileInputStream, Socket)
服务器端实现步骤:
- 创建一个服务器ServerSocket对象,和系统要指定的端口号
- 使用ServerSocket对象中的方法accept,获取到请求的客户端Socket对象
- 使用Socket对象中的方法getInputStream,获取到网络字节输入流InputStream对象
- 判断文件夹是否存在,不存在则创建
- 创建一个本地字节输出流FileOutputStream对象,构造方法中绑定要输出的目的地
- 使用网络字节输入流InputStream对象中的方法read,读取客户端上传的文件
- 使用本地字节输出流FileOutputStream对象中的方法write ,把读取到的文件保存到服务器的硬盘上
- 使用Socket对象中的方法getOutputStream,获取到网络字节输出流0utputStream对象
- 使用网络字节输出流0utputStream对象中的方法write,给客户端回写”上传成功”
- 释放资源(FileOutputStream, Socket, ServerSocket)
文件结构
. ├── img │ └── home01.jpeg ├── out │ └── production │ └── 基于JAVA的网络编程——socket文件传输 │ ├── FileUpload │ │ ├── TCPClient.class │ │ ├── TCPServer$1.class │ │ └── TCPServer.class │ └── UI │ ├── MainUI$1.class │ ├── MainUI$2.class │ ├── MainUI$3.class │ ├── MainUI$4$1.class │ ├── MainUI$4$2.class │ ├── MainUI$4.class │ ├── MainUI.class │ ├── Window$1.class │ ├── Window$2.class │ └── Window.class ├── receiveFile │ └── 2020-06-03 14:39:42计网实验.png ├── src │ ├── FileUpload │ │ ├── TCPClient.java │ │ └── TCPServer.java │ └── UI │ ├── MainUI.java │ └── Window.java └── 基于JAVA的网络编程——socket文件传输.iml
实现代码
home01.jpeg
package FileUpload;import java.io.*;import java.net.Socket;public class TCPClient{// private final String IP = "127.0.0.1";// private final int PORT = 8888;// private String send_file_path = "sendFile/ttt.png";public TCPClient(String IP, int PORT, String send_file_path, String send_file_name) throws IOException{init(IP, PORT, send_file_path, send_file_name);}private void init(String IP, int PORT, String send_file_path, String send_file_name) throws IOException{// 读取本地文件FileInputStream fis = new FileInputStream(send_file_path);Socket socket = new Socket(IP, PORT);OutputStream os = socket.getOutputStream();InputStream is = socket.getInputStream();// OutputStream oStream = socket.getOutputStream() ; //输出流// BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(oStream)) ;// //向服务器端发送一条消息// System.out.println("send_file_name:"+send_file_name);// bWriter.write(send_file_name) ;// bWriter.flush();DataOutputStream dos = new DataOutputStream(socket.getOutputStream());dos.writeUTF(send_file_name);//发给服务端System.out.println("send_file_name:" + send_file_name);int len = 0;byte[] bytes = new byte[1024];// 把读取到到文件上传到服务器while ((len = fis.read(bytes)) != -1){os.write(bytes, 0, len);}// 阻塞socket.shutdownOutput();// 回写while ((len = is.read(bytes)) != -1){System.out.println(new String(bytes, 0, len));}// 释放资源fis.close();socket.close();}public static void main(String[] args) throws IOException{TCPClient client = new TCPClient("127.0.0.1", 8888, "sendFile/ttt.png", "ttt.png");}}
package FileUpload;import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.text.SimpleDateFormat;import java.util.Date;public class TCPServer{public TCPServer() throws IOException{init();}private void init() throws IOException{final int PORT = 8888;final String receive_file_path = "receiveFile";ServerSocket server = new ServerSocket(PORT);while (true){Socket socket = server.accept();System.out.println("来访问客户端信息:" + "客户端IP:" + socket.getInetAddress()+ " 客户端端口:" + socket.getInetAddress().getLocalHost() + "已连接服务器");// BufferedReader bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端发送来的消息// String receive_file_name = bReader.readLine();// System.out.println("客户端发来的消息:" + msg);DataInputStream dis = new DataInputStream(socket.getInputStream());String receive_file_name = dis.readUTF();new Thread(new Runnable(){@Overridepublic void run(){try{InputStream is = socket.getInputStream();File file = new File(receive_file_path);if (!file.exists()){file.mkdir();}SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String receive_file_path = file + File.separator + df.format(new Date()) + receive_file_name;System.out.println("receive_file_name:" + receive_file_name);System.out.println("receive_file_path:" + receive_file_path);FileOutputStream fos = new FileOutputStream(receive_file_path);int len = 0;byte[] bytes = new byte[1024];while ((len = is.read(bytes)) != -1){fos.write(bytes, 0, len);}socket.getOutputStream().write("上传成功".getBytes());fos.close();socket.close();}catch (IOException e){e.printStackTrace();}}}).start();}// server.close();}public static void main(String[] args) throws IOException{TCPServer server = new TCPServer();}}
package UI;import javax.swing.*;import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class Window extends JFrame{public int width = Toolkit.getDefaultToolkit().getScreenSize().width;public int height = Toolkit.getDefaultToolkit().getScreenSize().height;// 定义窗体的宽高public int windowsWidth = 600;public int windowsHeight = 600;public void resize(int windowsWidth, int windowsHeight){// 设置窗体位置和大小super.resize(windowsWidth, windowsHeight);this.windowsHeight = windowsHeight;this.windowsHeight = windowsWidth;this.setBounds((width - windowsWidth) / 2,(height - windowsHeight) / 2, windowsWidth, windowsHeight);}public Window(String title){this.setTitle(title);// 关闭窗口this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent windowEvent){System.exit(0);}});}public Window(){this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent windowEvent){System.exit(0);}});}public static void main(String[] args){new Window().setVisible(true);}}
package UI;import FileUpload.TCPClient;import FileUpload.TCPServer;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.File;import java.io.IOException;public class MainUI{private Window MainWindow;private JPanel panel1;private JLabel header_label;private JLabel statusLabel;private JLabel img_label;private ImageIcon icon;private JButton select_file_btn;private JButton ok_btn;private String img_path = "img/home01.jpeg";private TextField IP_edit;private TextField PORT_edit;private JLabel IP_label;private JLabel PORT_label;private String send_file_name;private String send_file_path;private String IP;private int PORT;public MainUI(){initUI();}private void initUI(){icon = new ImageIcon(img_path);header_label = new JLabel("欢迎使用文件传输", JLabel.CENTER);img_label = new JLabel("", icon, JLabel.CENTER);statusLabel = new JLabel("", JLabel.CENTER);IP_label = new JLabel("服务器IP:", JLabel.RIGHT);PORT_label = new JLabel("服务器PORT:", JLabel.CENTER);IP_edit = new TextField();PORT_edit = new TextField();// IP_edit.addActionListener(new ActionListener()// {// public void actionPerformed(ActionEvent e)// {// IP = IP_edit.getText();// }// });// PORT_edit.addActionListener(new ActionListener()// {// public void actionPerformed(ActionEvent e)// {// PORT = Integer.parseInt(PORT_edit.getText());// }// });IP_edit.addKeyListener(new KeyListener(){@Overridepublic void keyTyped(KeyEvent e){IP = IP_edit.getText();System.out.println("IP:" + IP);}@Overridepublic void keyPressed(KeyEvent e){IP = IP_edit.getText();System.out.println("IP:" + IP);}@Overridepublic void keyReleased(KeyEvent e){IP = IP_edit.getText();System.out.println("IP:" + IP);}});PORT_edit.addKeyListener(new KeyListener(){@Overridepublic void keyTyped(KeyEvent e){// PORT = Integer.parseInt(PORT_edit.getText());System.out.println("PORT:" + PORT_edit.getText());}@Overridepublic void keyPressed(KeyEvent e){// PORT = Integer.parseInt(PORT_edit.getText());System.out.println("PORT:" + PORT_edit.getText());}@Overridepublic void keyReleased(KeyEvent e){// PORT = Integer.parseInt(PORT_edit.getText());System.out.println("PORT:" + PORT_edit.getText());}});final JFileChooser fileDialog = new JFileChooser();select_file_btn = new JButton("选择上传文件");ok_btn = new JButton("确定上传");select_file_btn.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e){int returnVal = fileDialog.showOpenDialog(MainWindow);if (returnVal == JFileChooser.APPROVE_OPTION){File file = fileDialog.getSelectedFile();send_file_name = file.getName();statusLabel.setText("选择上传文件:" + send_file_name);send_file_path = file.getAbsolutePath();}else{statusLabel.setText("取消打开文件");}}});ok_btn.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e){new Thread(new Runnable(){@Overridepublic void run(){try{// System.out.println(send_file_name);TCPServer server = new TCPServer();}catch (IOException ioException){ioException.printStackTrace();}}}).start();new Thread(new Runnable(){@Overridepublic void run(){try{PORT = Integer.parseInt(PORT_edit.getText());TCPClient client = new TCPClient(IP, PORT, send_file_path, send_file_name);statusLabel.setText("上传成功");}catch (IOException ioException){statusLabel.setText("上传失败");ioException.printStackTrace();}}}).start();}});panel1 = new JPanel();panel1.setLayout(new GridLayout(0, 4));header_label.setFont(new Font("Arial", Font.BOLD, 17));IP_label.setFont(new Font("Arial", Font.BOLD, 15));PORT_label.setFont(new Font("Arial", Font.BOLD, 15));// 布局MainWindow = new Window("文件传输");MainWindow.resize(640, 520);MainWindow.setLayout(new FlowLayout());panel1.add(IP_label, BorderLayout.WEST);panel1.add(IP_edit, BorderLayout.EAST);panel1.add(PORT_label, BorderLayout.EAST);panel1.add(PORT_edit, BorderLayout.WEST);panel1.add(new JLabel(""));panel1.add(select_file_btn, BorderLayout.WEST);panel1.add(new JLabel(""));panel1.add(ok_btn, BorderLayout.EAST);IP = IP_edit.getText();System.out.println(IP);MainWindow.add(header_label);MainWindow.add(img_label);MainWindow.add(panel1);MainWindow.add(statusLabel);MainWindow.setVisible(true);}public static void main(String[] args){MainUI mainUI = new MainUI();}}