python 套接字OSError : [Errno 107] Transport endpoint is not connected

标签 python sockets

所以我一直在制作一个带有客户端和服务器的套接字文件传输脚本。服务器有客户端可以请求的文件,这里是代码。

#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')

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

最佳答案

这里有两个套接字:第一个是在您的服务器 main 中称为 s 的套接字。这是一个监听 套接字,它是您用来接受 新连接的套接字。 accept 调用返回另一个套接字(您将其命名为 conn)。

conn 套接字连接到您的对等点,您可以使用它向对等点发送 和从对等点接收recvs 套接字连接,您既不能在其上发送 也不能接收。因此,您甚至没有理由将 s 传递给您的 loop 函数。此时您可以对 s 做的唯一重要的事情是关闭它,或者接受它上面的更多连接。

关于 python 套接字OSError : [Errno 107] Transport endpoint is not connected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980918/

相关文章:

php - 如何读取从 PHP 通过套接字发送到 Qt 服务器应用程序的字符串?

c++ - boost::asio::ip::tcp::socket - 如何绑定(bind)到特定的本地端口

java - 在socket编程中如何判断服务器发送数据成功?

python - setitem 和 getitem -- python

python - 使用 scipy generic_filter 和 numpy Median_filter 计算移动中位数会给出不同的输出

python - 通过反斜杠分割在 selenium python 中获得的文本时出错

java - Java 中的 UDP/TCP 段分段

python - 在Linux上使用python接收多播UDP数据报

python - 为什么 try-finally 有效,但 try-else-finally 无效?

python - 写入打开的 CSV 时跳过 header