【问题标题】:TypeError: %d format: a number is required, not str getting this error while creating port listenTypeError: %d format: a number is required, not str 在创建端口监听时收到此错误
【发布时间】:2021-01-11 17:30:38
【问题描述】:

为什么我从谷歌复制了正确的代码后出现此错误如何解决此错误。

import socket
import threading

bind_ip = "0.0.0.0"
bind_port = 9999

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[-#-]  Listening on %s:%d" % (bind_port, bind_ip))

# this is our clint-hanadaling thread


def handle_client(client_socket):
    # print out what client sends
    request = client_socket.recv(1024)
    print("[* ] Received %s " % request)
    # send back a request
    client_socket.send("ACK!")
    client_socket.close()
    while True:
        client, addr = server.accept()
        print("[*] Accepted connection from %s:%d" % (addr[0], addr[1]))
        # spin up our client thread  to handle incoming data
        clinet_handler = threading.Thread(target=handle_client, args=client)
        clinet_handler.start()

在以下位置出现错误:Traceback(最近一次调用最后一次):文件 “c:/Users/Najuser/Desktop/PYThon/tcp.py”,第 10 行,在 print("[-#-] Listening on %s:%d" % (bind_port, bind_ip)) TypeError: %d format: a number is required, not str

【问题讨论】:

    标签: python python-3.x ip string-formatting


    【解决方案1】:

    改变

    print("[-#-]  Listening on %s:%d" % (bind_port, bind_ip))
    

    print("[-#-]  Listening on %s:%d" % (bind_ip,bind_port))
    

    字符串格式化程序 %d 需要一个数字,但 bind_ip 是一个字符串。要打印的值顺序错误

    【讨论】:

    • @gordin 一个问题,为什么它只是在监听而不是从客户端发送任何响应
    • 尝试从while True: 的行开始取消缩进。 while 循环不应该在handle_client 函数中。当新客户端连接到服务器时调用此函数。
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2018-06-18
    • 2021-12-05
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    相关资源
    最近更新 更多