利用Socket和IO流实现文件的上传与下载


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

背景概述

本文利用Socket编程和IO流技术实现文件的上传与下载。

核心技术

  • 1、TCP
  • 2、Socket
  • 3、FileInputStream与FileOutputStream
  • 4、DataInputStream与DataOutputStream
  • 5、多线程

Config

package com.io14;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class Config {
	public static final String ip = "localhost";
	public static final int port = 10088;
}

在这里插入图片描述

Client

package com.io14;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class Client {

	public static void main(String arg[]) {
		testDownload();
	}

	public static void testUpload() {
		String filePath = "D:" + File.separator + "beauty.jpg";
		Client client = new Client();
		client.uploadFile(filePath);
	}

	public static void testDownload() {
		Client client = new Client();
		client.downloadFile();
	}

	public void uploadFile(String filePath) {
		try {
			// 创建待上传文件对象
			File file = new File(filePath);
			String fileName = file.getName();
			long fileLength = file.length();
			System.out.println("客户端待上传文件:" + fileName + ",其大小为:" + fileLength);

			// 创建FileInputStream
			FileInputStream fileInputStream = new FileInputStream(filePath);

			// 创建Socket对象
			Socket socket = new Socket(Config.ip, Config.port);
			// 从Socket获取OutputStream
			OutputStream outputStream = socket.getOutputStream();
			// 创建DataOutputStream
			DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

			// 利用DataOutputStream写出文件名和文件大小
			dataOutputStream.writeUTF(fileName);
			dataOutputStream.writeLong(fileLength);
			dataOutputStream.flush();

			// IO流读写操作
			byte[] buf = new byte[1024 * 1];
			int len = 0;
			while ((len = fileInputStream.read(buf)) != -1) {
				dataOutputStream.write(buf, 0, len);
			}

			// 释放资源
			dataOutputStream.flush();
			fileInputStream.close();
			socket.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	public void downloadFile() {
		try {
			// 创建Socket对象
			Socket socket = new Socket(Config.ip, Config.port);
			// 从Socket获取InputStream
			InputStream inputStream = socket.getInputStream();
			// 创建DataInputStream对象
			DataInputStream dataInputStream = new DataInputStream(inputStream);

			// 获取下载文件的文件名和文件大小
			String fileName = dataInputStream.readUTF();
			long fileLength = dataInputStream.readLong();
			System.out.println("客户端下载文件:" + fileName + ",其大小为:" + fileLength);

			// 组拼文件保存路径
			String fileDir = "D:";
			String filePath = fileDir + File.separator + fileName;

			// 创建FileOutputStream对象
			FileOutputStream fileOutputStream = new FileOutputStream(filePath);

			// IO流读写操作
			byte[] buf = new byte[1024 * 1];
			int len = 0;
			while ((len = dataInputStream.read(buf)) != -1) {
				fileOutputStream.write(buf, 0, len);
			}

			// 释放资源
			fileOutputStream.flush();
			fileOutputStream.close();
			dataInputStream.close();
			socket.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}

在这里插入图片描述

Server

package com.io14;

import java.net.ServerSocket;
import java.net.Socket;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class Server {
	public static void main(String arg[]) {
		testDownload();
	}
	
	public static void testUpload() {
		Server server = new Server();
		server.handleUploadFile();
	}
	
	public static void testDownload() {
		Server server = new Server();
		server.handleDownloadFile();
	}

	public void handleUploadFile() {
		try {
			// 创建ServerSocket对象
			ServerSocket serverSocket = new ServerSocket(Config.port);
			while (true) {
				// 接收客户端连接请求
				Socket socket = serverSocket.accept();
				// 开启子线程处理文件上传
				UploadRunnableImpl uploadRunnableImpl = new UploadRunnableImpl(socket);
				Thread thread = new Thread(uploadRunnableImpl);
				thread.start();
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

	public void handleDownloadFile() {
		try {
			// 创建ServerSocket对象
			ServerSocket serverSocket = new ServerSocket(Config.port);
			while (true) {
				// 接收客户端连接请求
				Socket socket = serverSocket.accept();
				// 开启子线程处理文件下载
				DownloadRunnableImpl downloadRunnableImpl = new DownloadRunnableImpl(socket);
				Thread thread = new Thread(downloadRunnableImpl);
				thread.start();
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}

在这里插入图片描述

UploadRunnableImpl

package com.io14;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class UploadRunnableImpl implements Runnable {
	private Socket socket;
	
	public UploadRunnableImpl(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			// 从Socket获取InputStream
			InputStream inputStream = socket.getInputStream();
			// 创建DataInputStream对象
			DataInputStream dataInputStream = new DataInputStream(inputStream);
			
			// 获取上传文件的文件名和文件大小
			String fileName = dataInputStream.readUTF();
			long fileLength = dataInputStream.readLong();
			System.out.println("服务端接收上传文件:"+fileName+",其大小为:"+fileLength);
			
			// 组拼文件保存路径
			String fileDir = "E:";
			String filePath= fileDir + File.separator+fileName;
			
			// 创建FileOutputStream对象
			FileOutputStream fileOutputStream = new FileOutputStream(filePath);
			
			// IO流读写操作
			byte[] buf = new byte[1024*1];
			int len = 0;
			while ((len = dataInputStream.read(buf)) != -1) {
				fileOutputStream.write(buf, 0, len);
			}
			
			// 释放资源
			fileOutputStream.flush();
			fileOutputStream.close();
			dataInputStream.close();
			socket.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

}

在这里插入图片描述

DownloadRunnableImpl

package com.io14;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class DownloadRunnableImpl implements Runnable{
	private Socket socket;
	
	public DownloadRunnableImpl(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			// 创建待下载文件对象
			String filePath = "E:"+File.separator+"beauty.jpg";
			File file = new File(filePath);
			String fileName = file.getName();
			long fileLength = file.length();
			System.out.println("服务端待下载文件:" + fileName + ",其大小为:" + fileLength);

			// 创建FileInputStream
			FileInputStream fileInputStream = new FileInputStream(filePath);

			// 从Socket获取OutputStream
			OutputStream outputStream = socket.getOutputStream();
			// 创建DataOutputStream
			DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

			// 利用DataOutputStream写出文件名和文件大小
			dataOutputStream.writeUTF(fileName);
			dataOutputStream.writeLong(fileLength);
			dataOutputStream.flush();

			// IO流读写操作
			byte[] buf = new byte[1024 * 1];
			int len = 0;
			while ((len = fileInputStream.read(buf)) != -1) {
				dataOutputStream.write(buf, 0, len);
			}

			// 释放资源
			dataOutputStream.flush();
			fileInputStream.close();
			socket.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}

在这里插入图片描述

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Socket.IO 是一个基于 Node.js 的实时应用程序框架,可以轻松地实现实时通信和数据传输。如果您想要在 Socket.IO实现私聊功能,可以按照以下步骤进行: 1. 在客户端中,当用户点击其他用户的用户名时,将该用户名作为参数发送到服务器端。 2. 在服务器端,监听客户端发送的私聊请求,并将其转发给目标用户。 3. 在客户端中,监听服务器端发送的私聊消息,并将其显示在用户界面中。 下面是一个简单的示例代码: 服务端代码: ``` const app = require('http').createServer(); const io = require('socket.io')(app); io.on('connection', (socket) => { console.log('a user connected'); // 监听私聊请求 socket.on('private message', (data) => { const targetSocket = io.sockets.connected[data.targetId]; if (targetSocket) { targetSocket.emit('private message', data); } }); }); app.listen(3000, () => { console.log('listening on *:3000'); }); ``` 客户端代码: ``` const socket = io('http://localhost:3000'); // 发送私聊请求 socket.emit('private message', { targetId: 'targetUserId', message: 'Hello, target user!' }); // 监听私聊消息 socket.on('private message', (data) => { console.log(`Received private message from ${data.senderId}: ${data.message}`); }); ``` 在这个示例中,服务端监听客户端发送的 `private message` 事件,并将其转发给目标用户。客户端发送私聊请求时,将目标用户的 ID 和消息内容作为参数发送到服务器端。当客户端收到私聊消息时,将其显示在用户界面中。 当然,这只是一个简单的示例,实际应用中还需要考虑很多其他因素,例如身份验证、消息存储等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷哥的小弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值