使用套接字在python中命名文件

时间:2017-11-28 18:31:50

标签: python-3.x python-sockets

我正在创建一个文件,您可以将文件发送到远程Ubuntu服务器。 然而,当我发送它的名字时,我把它打印出来,它只是" B'' " 我怎么做才能打开文件?

Client.py

import socket
with socket.socket() as s:
    s.connect(('139.59.173.187',8000))
    with open('User.txt','rb') as f:
        s.sendall(f.read())
    name = input("What would you like it to be saved as?")
    s.send(name)

Server.py

import socket
with socket.socket() as s:
    s.connect(('139.59.173.187',8000))
    with open('User.txt','rb') as f:
        s.sendall(f.read())
    name = input("What would you like it to be saved as?")
    s.send(name)

提前致谢

`

1 个答案:

答案 0 :(得分:0)

  1. 您的server.py和client.py文件都相同。我认为你错误地复制了它们。
  2. 关于问题:
  3. 尝试首先将名称发送到远程服务器

  4. clients.py(在python3中)

    import socket
    
    with socket.socket() as s:
        s.connect(('127.0.0.1',22599))
    
        name = input("What would you like it to be saved as?")
    
        s.send(name.encode('utf-8'))
    
        with open('xyz.txt','rb') as f:
            s.sendall(f.read())
    
  5. server.py(在python2.7中)

    import socket   # Import socket module
    s = socket.socket()         
    host = '127.0.0.1' #Ge Local Machine
    port = 22599               
    s.bind((host, port)) # Bind to the port
    s.listen(3)    #wait for client to join
    while True:
        c, addr = s.accept()     
        print 'Connection Accepted From',addr
        print "File is comming ...."
        file = c.recv(1024)     #get file name first from client
        #opening file first
    
        f = open(file,'wb')      #open that file or create one
        l = c.recv(1024)         #get input
        while (l):
    
            print "Receiving...File Data"
            f.write(l)            #save input to file
            l = c.recv(1024)      #get again until done
    
        f.close()
    
    c.send('Thank you for connecting')
    c.close()
    
  6. 谢谢