实现同一WiFi下用户信息展示和文件传输的功能,可以使用一些现有的开源项目和库来加速开发。以下是一些可能有用的开源项目和库:
1. LAN Share
LAN Share 是一个简单且快速的跨平台工具,用于在局域网内共享文件和文件夹。它有以下特点:
- 跨平台(Linux 和 Windows)
- 简单易用的 GUI
- 支持大文件传输
2. ShareDrop
ShareDrop 是一个基于 Web 的开源应用,可以让你在同一网络中的设备之间分享文件。它的特点是:
- 不需要安装任何软件
- 使用 WebRTC 技术直接在浏览器中传输文件
- 支持多平台
3. Snapdrop
Snapdrop 是另一个基于 WebRTC 的文件传输工具,类似于 ShareDrop。它的特点是:
- 开源且易于部署
- 跨平台支持
- 简单易用的界面
4. LocalSend
LocalSend 是将文件分享到附近的设备包括移动设备、电脑、平板。它的特点是:
- 跨平台LocalSend可用于Windows、macOS、Linux、Android和iOS。
- 免费LocalSend免费使用。无广告、无跟踪、无隐藏付费。
- 简单易用的界面
Python实现一个局域网文件互传工具
使用 Flask 和 Python 来实现这个功能,一个简单的例子,展示如何使用 Flask 和 Flask-SocketIO 来实现文件传输和用户信息展示。
依赖项
首先安装必要的依赖项:
pip install Flask Flask-SocketIO eventlet flask-uploads
app.py
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_socketio import SocketIO, emit
from flask_uploads import UploadSet, configure_uploads, ALL
import time
app = Flask(__name__)
socketio = SocketIO(app)
# Configuring file uploads
files = UploadSet('files', ALL)
app.config['UPLOADED_FILES_DEST'] = 'uploads'
configure_uploads(app, files)
users = {} # Dictionary to store user information
@app.route('/')
def index():
return render_template('index.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOADED_FILES_DEST'], filename)
@app.route('/register', methods=['POST'])
def register():
data = request.json
ip = request.remote_addr
users[ip] = {'ip': ip, 'local_ip': data['local_ip'], 'timestamp': time.time()}
socketio.emit('user_update', users, broadcast=True)
return jsonify(success=True)
@socketio.on('connect')
def handle_connect():
ip = request.remote_addr
users[ip] = {'ip': ip, 'sid': request.sid, 'timestamp': time.time()}
socketio.emit('user_update', users, broadcast=True)
@socketio.on('disconnect')
def handle_disconnect():
ip = request.remote_addr
users.pop(ip, None)
socketio.emit('user_update', users, broadcast=True)
@socketio.on('send_file')
def handle_send_file(data):
receiver_ip = data['receiver_ip']
filename = data['filename']
if receiver_ip in users:
emit('receive_file', {'filename': filename}, room=users[receiver_ip]['sid'])
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Send</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.min.js"></script>
</head>
<body>
<h1>Local Send</h1>
<h2>Users in the same network:</h2>
<ul id="users"></ul>
<input type="file" id="fileInput">
<button id="sendFileButton">Send File</button>
<script>
const socket = io();
const usersList = document.getElementById('users');
const fileInput = document.getElementById('fileInput');
const sendFileButton = document.getElementById('sendFileButton');
let selectedUserIp = null;
function getLocalIP(callback) {
const peerConnection = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});
peerConnection.createDataChannel("");
peerConnection.createOffer().then(offer => peerConnection.setLocalDescription(offer));
peerConnection.onicecandidate = event => {
if (!event || !event.candidate) {
return;
}
const parts = event.candidate.candidate.split(" ");
const localIP = parts[4];
if (localIP.match(/([0-9]{1,3}\.){3}[0-9]{1,3}/)) {
callback(localIP);
peerConnection.close();
}
};
}
getLocalIP(localIP => {
fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ local_ip: localIP })
}).then(response => response.json())
.then(data => console.log('Registration success:', data))
.catch(error => console.error('Registration error:', error));
});
socket.on('user_update', (users) => {
usersList.innerHTML = '';
for (const [ip, user] of Object.entries(users)) {
const userItem = document.createElement('li');
userItem.textContent = `${user.local_ip} (${ip})`;
userItem.onclick = () => {
selectedUserIp = ip;
document.querySelectorAll('#users li').forEach(li => li.style.fontWeight = 'normal');
userItem.style.fontWeight = 'bold';
};
usersList.appendChild(userItem);
}
});
sendFileButton.onclick = () => {
if (selectedUserIp && fileInput.files.length > 0) {
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData
}).then(response => response.json())
.then(data => {
socket.emit('send_file', { receiver_ip: selectedUserIp, filename: data.filename });
}).catch(error => console.error('Upload error:', error));
} else {
alert('Please select a user and a file.');
}
};
socket.on('receive_file', (data) => {
const link = document.createElement('a');
link.href = `/uploads/${data.filename}`;
link.download = data.filename;
link.textContent = `Download ${data.filename}`;
document.body.appendChild(link);
});
</script>
</body>
</html>
使用 Gunicorn 运行
使用 Gunicorn 作为生产服务器来运行这个 Flask 应用:
gunicorn --worker-class eventlet -w 1 -b 0.0.0.0:5000 app:app
如果您找不到或不想找,关注公众号TeachCourse,回复关键字获取,比如:LocalSend
当前文章价值6.68元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

评论已关闭!