使用python套接字将Txt文件从客户端发送到服务器

使用python套接字将Txt文件从客户端发送到服务器

本文介绍了使用python套接字将Txt文件从客户端发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用用于发送文本和其他媒体文件的套接字在python中创建服务器/客户端.方案:-客户端将主机,端口和文件名作为参数并将文件发送到服务器.错误描述:-,尝试执行以下客户端代码时,文本文件"tos"与客户端位于同一目录中.得到以下错误.

i am trying to create a server/client in python using sockets for sending text and other media files.Scenario:- Client takes host, port and file name as parameters and send the file to server.Error Description:- while trying to execute the below client code, having text file "tos" in same directory as client.Getting below error.

**$ python Cli.py 127.0.0.1 5007 tos**
Traceback (most recent call last):
  File "Cli.py", line 32, in <module>
    client= Client(host,port,file)
  File "Cli.py", line 15, in __init__
    self.connect(file)
  File "Cli.py", line 20, in connect
    self.sendFile(file)
  File "Cli.py", line 26, in sendFile
    readByte = open(file, "rb")
**IOError: [Errno 2] No such file or directory: ''**

注意:-还请说明是否仍然存在将文件发送到服务器,搜索硬盘驱动器的情况.

Note:- Also please describe if there is anyway to send file to server, searching the hard drive.

服务器:-

from socket import *
port = 5007
file = ''
class Server:
    gate = socket(AF_INET, SOCK_STREAM)
    host = '127.0.0.1'
    def __init__(self, port):
        self.port = port
        self.gate.bind((self.host, self.port))
        self.listen()

    def listen(self):
        self.gate.listen(10)
        while True:
            print("Listening for connections, on PORT: ", self.port)
            add = self.gate.accept()
            self.reciveFileName()
            self.reciveFile()


    def reciveFileName(self):
        while True:
            data = self.gate.recv(1024)
            self.file = data

    def reciveFile(self):
        createFile = open("new_"+self.file, "wb")
        while True:
            data = self.gate.recv(1024)
            createFile.write(data)
        createFile.close()
server= Server(port)
listen()

客户:-

 #!/usr/bin/env python
from socket import *
host = ''
port = 5007
file = ''
class Client:
    gateway = socket(AF_INET, SOCK_STREAM)
    def __init__(self, host,port, file):
        self.port = port
        self.host = host
        self.file = file
        self.connect()

    def connect(self):
        self.gateway.connect((self.host, self.port))
        self.sendFileName(file)
        self.sendFile(file)

    def sendFileName(self):
        self.gateway.send("name:" +self.file)

    def sendFile(self):
        readByte = open(self.file, "rb")
        data = readByte.read()
        readByte.close()

        self.gateway.send(data)
        self.gateway.close()
client= Client(host,port,file)
connect()

推荐答案

目前file = ''中的文件名无效.为了清楚起见,我还建议将file重命名为filename.

At the moment file = '' which in not a valid filename. I would also suggest renaming file to filename for clarity.

这篇关于使用python套接字将Txt文件从客户端发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:01