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

时间:2018-01-29 08:16:43

标签: python python-3.x sockets

从客户端我尝试将txt文件发送到服务器。

client.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()

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()

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

有人可以告诉我程序中有什么问题吗?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案

请注意我们的声明,即只有在套接字处于阻塞模式时才会阻止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