Python Socket编程:文件传输代码分析与错误调试

以下代码片段展示了使用 Python Socket 模块实现文件传输的示例:

import socket
import os

def sendfile(conn):
    strl = conn.recv(1024)
    filename = strl.decode('utf-8')
    print('The client requests my file:', filename)
    if os.path.exists(filename):
        print('I have ' + filename + ',begin to download!')
        conn.send(b'yes')
        conn.recv(1024)
        size = 1024
        with open(filename, 'rb') as f:
            while True:
                data = f.read(size)
                conn.send(data)
                if len(data) < size:
                    break
    print(''' + filename + '' is downloaded successfully!')
    conn.close()
else:
    print('Sorry,I have no ' + filename + '!')
    conn.send(b'no')
    conn.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.3.201', 8088))
s.listen(1)
print('Wait for connecting...')
while True:
    (conn, addr) = s.accept()
    sendfile(conn)

代码第 13 行语句的语法错误

代码第 13 行语句 print('I have%s,begin to download!'% filename) 中包含一个多余的中文符号“、”。 Python 语法中,字符串使用单引号或双引号包裹,而中文符号“、”并非有效的字符串分隔符。因此,该行代码会导致语法错误,程序无法正常运行。

解决方法

将代码第 13 行改为以下语句,即可解决语法错误:

print('I have ' + filename + ',begin to download!')

修改后的代码:

import socket
import os

def sendfile(conn):
    strl = conn.recv(1024)
    filename = strl.decode('utf-8')
    print('The client requests my file:', filename)
    if os.path.exists(filename):
        print('I have ' + filename + ',begin to download!')
        conn.send(b'yes')
        conn.recv(1024)
        size = 1024
        with open(filename, 'rb') as f:
            while True:
                data = f.read(size)
                conn.send(data)
                if len(data) < size:
                    break
    print(''' + filename + '' is downloaded successfully!')
    conn.close()
else:
    print('Sorry,I have no ' + filename + '!')
    conn.send(b'no')
    conn.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.3.201', 8088))
s.listen(1)
print('Wait for connecting...')
while True:
    (conn, addr) = s.accept()
    sendfile(conn)

总结

本文通过分析 Python Socket 文件传输代码,解释了代码中出现的语法错误,并提供了解决方法。希望能够帮助读者更好地理解 Python 代码中的语法规则,提高代码调试效率。


原文地址: https://www.cveoy.top/t/topic/oCpw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录