Python套接字错误: [Errno 107] 传输端点未连接

3

我正在制作一个具有客户端和服务器的套接字文件传输脚本。服务器拥有客户端可以请求的文件,以下是代码。

#server.py
import socket
import os
host = '127.0.0.1'
port = 5000
#defining the stuff we want to use
#all the files you can download are stored here
def main():
    file_folder = '/home/lario/Desktop/pyprojects/networking/filetransfer/files/'

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print('Server started on {}:{}'.format(host, str(port)))
    s.listen(5)
    sentace = 'We have these files for you to download: '
    while True:
        conn, addr = s.accept()
        print('[*] Got a connection from {}'.format(addr))
        loop(file_folder, sentace, conn, s, os.listdir(file_folder))
        print('[*] File transfer with {} has been succesfull')
    s.close()

def loop(file_folder, sentace, conn, socket, existing_files):
    #sends which files we have to download for the client
    conn.send(sentace.encode('utf-8') + str(existing_files).encode('utf-8'))
    #gets response which one he wants to download
    data = socket.recv(4096)
    #gets path of the file
    file_place = file_folder + data.decode('utf-8')
    #checks if file exists
    if os.path.isfile(file_place):
        #asks if he wants to download it
        succes = '[+] The file exists, it has {} still wish to download?'.format(os.path.getsize(file_place)).encode('utf-8')
        conn.send(succes)
        data = socket.recv(4096).decode('utf-8')
        #if response is yes send him the file
        if data.lower() == 'y':
            with open(file_place, 'rb') as f:
                file_data = f.read(4096)
                conn.send(file_data)
        else:
            pass


    else:
        succes = '[-] The file doesn\'t exist. Try again'
        conn.send(succes.encode('utf-8'))
        loop(file_folder, sentace, conn, socket, existing_file)


#client.py
import socket
def main():
    ip = '127.0.0.1'
    port = 5000
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
    print('[*] Connected to server')
    data = s.recv(1024)
    print(data.decode('utf-8'))
    file_down = input('-->')
    s.send(file_down.encode('utf-8'))
    data = s.recv(4096)
    if data[1] == '+':
        data = s.recv(4096)
        print(data.decode('utf-8'))
        choice = input("Y/N").lower()
        if choice == 'y':
            s.send(choice.encode('utf-8'))
            prefix = input('What kind of prefix do you want for your files: ')
            with open(str(prefix + file_down), 'wb') as f:
                data = s.recv(4096)
                f.write(data)
        elif choice == 'n':
            s.send(choice.encode('utf-8'))
            print('Well, see you next time.')
        else:
            s.send(choice.encode('utf-8'))
            print('Not a valid input.')

    else:
        print('File doesn\'t exist.')


main()

这是输出结果。

#server
Server started on 127.0.0.1:5000
[*] Got a connection from ('127.0.0.1', 47170)
Traceback (most recent call last):
  File "server.py", line 48, in <module>
    main()
  File "server.py", line 17, in main
    loop(file_folder, sentace, conn, s, os.listdir(file_folder))
  File "server.py", line 25, in loop
    data = socket.recv(4096).decode('utf-8')
OSError: [Errno 107] Transport endpoint is not connected

#client
[*] Connected to server
We have these files for you to download: ['syria.txt', 'eye.jpg', 'kim-jong.jpg']
-->

您会看到我在变量中有字符串,我这样做是因为您无法像这样对字符串进行编码。

'this is a string'.encode('utf-8')

客户端应该选择一个带有前缀的文件,并将该文件写入另一个文件中。
2个回答

3
这里有两个套接字:第一个是你的服务器主函数中称为s的套接字。这是一个监听套接字,用于accept新连接。accept调用返回另一个套接字(你命名为conn)。 conn套接字连接到你的同行,你可以使用它来sendrecv数据。s套接字未连接,你不能在其上进行sendrecv操作。因此,在你的loop函数中甚至没有必要传递s。此时,你唯一能够对s做的重要事情是将其close或在其上accept更多的连接。

好的,非常感谢,我现在明白了,我会进行更改。 - user8560436

0
以下是更新后的代码。需要使用conn而不是socket。
#server.py
import socket
import os
host = '127.0.0.1'
port = 5002
#defining the stuff we want to use
#all the files you can download are stored here
def main():
    file_folder = '<Path To Directory>'

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print('Server started on {}:{}'.format(host, str(port)))
    s.listen(5)
    sentace = 'We have these files for you to download: '
    while True:
        conn, addr = s.accept()
        print('[*] Got a connection from {}'.format(addr))
        loop(file_folder, sentace, conn, s, os.listdir(file_folder))
        print('[*] File transfer with {} has been succesfull')
    s.close()

def loop(file_folder, sentace, conn, socket, existing_files):
    #sends which files we have to download for the client
    conn.send(sentace.encode('utf-8') + str(existing_files).encode('utf-8'))
    #gets response which one he wants to download
    data = conn.recv(100000)
    #gets path of the file
    file_place = file_folder + data.decode('utf-8')
    #checks if file exists
    if os.path.isfile(file_place):
        #asks if he wants to download it
        succes = '[+] The file exists, it has {} still wish to download?'.format(os.path.getsize(file_place)).encode('utf-8')
        conn.send(succes)
        print ("CheckPoint 1 in Server")
        data = conn.recv(4096)
        #if response is yes send him the file
        if data.lower() == 'y':
            with open(file_place, 'rb') as f:
                file_data = f.read(4096)
                conn.send(file_data)
        else:
            pass


    else:
        succes = '[-] The file doesn\'t exist, Try again'
        conn.send(succes.encode('utf-8'))
        loop(file_folder, sentace, conn, socket, existing_file)

main()

Client.py

#client.py
import socket
def main():
    ip = '127.0.0.1'
    port = 5002
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
    print('[*] Connected to server')
    data = s.recv(100000)
    print(data.decode('utf-8'))
    file_down = input('-->')
    s.send(file_down.encode('utf-8'))
    data = s.recv(4096)
    print (data)
    if data[1] == '+':
        data = s.recv(4096)
        print(data.decode('utf-8'))
        print("Reached here in Client 1")
        choice = input("Y/N").lower()
        if choice == 'y':
            s.send(choice)
            prefix = input('What kind of prefix do you want for your files: ')
            with open(str(prefix + file_down), 'wb') as f:
                data = s.recv(4096)
                f.write(data)
        elif choice == 'n':
            s.send(choice.encode('utf-8'))
            print('Well, see you next time.')
        else:
            s.send(choice.encode('utf-8'))
            print('Not a valid input.')

    else:
        print('File doesn\'t exist.')


main()

客户端输出

We have these files for you to download: ['pDiffCompare.py', 'lib', 'g.jar']
-->'pDiffCompare.py'
[+] The file exists, it has 2296 still wish to download?
y

服务器端输出

Server started on 127.0.0.1:5002
[*] Got a connection from ('127.0.0.1', 38702)
CheckPoint 1 in Server
[*] File transfer with {} has been succesfull

好的,非常感谢。我的脚本还有一些小问题,但我现在会立即修复它。 - user8560436
是的。确实存在一些问题,但由于缺乏充分的数据和需求,无法解决。 - Manoj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接