python - 客户端通过socket向服务器发送文件

标签 python python-2.7

我编写了一个客户端和一个服务器程序,其中客户端向服务器发送文件,服务器打印文件的内容。这是代码片段:

Server---------------->serverprog.py

import socket
from threading import *


class Server:
    gate = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 0
    file = ''

    def __init__(self, port):
        self.port = port
    #        self.gate.bind((self.host, self.port))  
        self.gate.bind(("127.0.0.1", self.port))
        self.listen()
    def listen(self):
        self.gate.listen(10)
        while True:
            conn,address = self.gate.accept()
            self.receiveFilename(conn)
    def receiveFileName(self, sock):
        buf = sock.recv(1024)
        print('First bytes I got: ' + buf)

a = Server(8888)




Client ------------------>clientprog.py

import socket
from threading import *

class Client:
    gateway = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #host = socket.gethostname()
    host = ''
    port = 0
    file = ''

    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()
        self.sendFile()

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



a = Client('127.0.0.1', 8888, 'datasend.txt')

如果我同时编译客户端和服务器,它会给我服务器程序以下错误:

    Traceback (most recent call last):
  File "receivefilepg.py", line 25, in <module>
    a = Server(8888)
  File "receivefilepg.py", line 15, in __init__
    self.listen()
  File "receivefilepg.py", line 20, in listen
    self.receiveFilename(conn)
AttributeError: Server instance has no attribute 'receiveFilename'

我在这里做错了什么?任何建议都会有帮助!

最佳答案

该错误告诉您所有您需要知道的信息,您在 server.listen 方法中存在拼写错误,而不是调用 self.receiveFileName ,而是调用了 self .receiveFilename.

关于python - 客户端通过socket向服务器发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915161/

相关文章:

python - 在上下文管理器 __enter__() 中捕获异常

python-2.7 - Matplotlib 缩放后的图形大小和位置

python匹配正则表达式

python - SQLAlchemy 和原始 SQL : List as an input

python - 绘制前 10 名与所有其他值的对比图

javascript - 从 ASX 页面抓取表格

Python:帮助(numpy)导致退出时出现段错误

python - python中区分乱码/错误和外来词/名称的算法或工具?

python - 在 vscode 中运行单个文件夹的 pytest 测试

python - 如何使用 PycURL 保持非事件连接打开?