基于socket進(jìn)行文件傳輸?shù)倪^程可以分為以下幾個(gè)步驟:
listen()
方法。accept()
方法。以下是一個(gè)簡(jiǎn)單的示例代碼:
服務(wù)器端代碼:
import socket
# 創(chuàng)建socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 綁定IP地址和端口號(hào)
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 開始監(jiān)聽
server_socket.listen()
# 接受客戶端連接請(qǐng)求
client_socket, addr = server_socket.accept()
# 接收文件數(shù)據(jù)并保存到本地文件
with open('received_file.txt', 'wb') as file:
while True:
data = client_socket.recv(1024)
if not data:
break
file.write(data)
# 關(guān)閉連接
client_socket.close()
server_socket.close()
客戶端代碼:
import socket
# 創(chuàng)建socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 連接服務(wù)器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 打開要傳輸?shù)奈募?/span>
with open('file_to_send.txt', 'rb') as file:
# 讀取文件數(shù)據(jù)并發(fā)送給服務(wù)器
while True:
data = file.read(1024)
if not data:
break
client_socket.sendall(data)
# 關(guān)閉連接
client_socket.close()
以上示例代碼僅展示了最基本的文件傳輸過程,實(shí)際應(yīng)用中可能需要處理更多的異常情況、加入數(shù)據(jù)校驗(yàn)和安全驗(yàn)證等。