gpt4 book ai didi

python - 无法从客户端/服务器发送文件 -socket pgm-Python 3

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:00 25 4
gpt4 key购买 nike

我正在尝试从客户端发送一个 txt 文件到服务器。

客户端.py

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024

server_addr = (TCP_IP, TCP_PORT)

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(server_addr)

file = open(r"C:\Users\sakthi\Desktop\Hi.txt",'r')

transfer = file.read(BUFFER_SIZE)

while transfer:
c.send(transfer.encode())
transfer = file.read(1024)

print (s.recv(BUFFER_SIZE).decode())

c.close()

服务器.py

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((TCP_IP, TCP_PORT))

s.listen(1)
conn, addr = s.accept()

final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')

while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)

k="file received"

conn.send(k.encode())

conn.close()

一旦收到文件,服务器将向客户端发送“文件已收到”消息。客户端将打印消息“文件已收到”并关闭连接

当我运行代码时,server.py 没有退出 while 循环

while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)

r = conn.recv(BUFFER_SIZE).decode() 持续监听新消息,但客户端已传输所有消息。

文件大小为1.14 KB

谁能告诉我我的程序出了什么问题吗?

最佳答案

我找到了解决办法

请注意我们的声明,recv() 会阻塞,直到有数据可供读取或发送方关闭连接为止,仅当套接字处于阻塞模式时才会保持连接。该模式是默认模式,但我们可以通过使用参数 0 调用 setblocking() 将套接字更改为非阻塞模式。

我修改了server.py

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((TCP_IP, TCP_PORT))

s.listen(1)
conn, addr = s.accept()

conn.setblocking(0)

final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')

while 1:
try:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
final.write(r)
print("received data:", r)
except:
break

k="file received"

conn.send(k.encode())

conn.close()

现在我可以接收文件并向客户端发送消息“文件已收到”,并且连接已关闭。

non-blocking socket,error is always

http://www.mws.cz/files/PyNet.pdf

关于python - 无法从客户端/服务器发送文件 -socket pgm-Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com