【问题标题】:python 'TypeError: argument must be string or read-only character buffer, not tuple'python'TypeError:参数必须是字符串或只读字符缓冲区,而不是元组'
【发布时间】:2016-03-02 19:47:42
【问题描述】:

我使用 python 2.7 编写了这段代码:

class LoadBalancerHandler:

    def __init__(self, file_name):
        self.server_socket = socket.socket(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        file = open(file_name)
        setup_apps(file.read())

    def listen(self, host='localhost', port=80):
        self.server_socket.bind((host,port))
        self.server_socket.listen(5)
        while True:
            (client_socket, address) = self.server_socket.accept()
            threadHandling = ThreadHandling(client_socket, self)
            threadHandling.start()

但我收到此错误:

TypeError:参数必须是字符串或只读字符缓冲区,而不是元组

此错误由以下行引发:self.server_socket.bind((host,port))

【问题讨论】:

  • 您对 socket.socket(...) 的选择似乎很可疑。见docs.python.org/2/library/socket.html。你的意思可能是 socket.socket(socket.AF_INET, socket.SOCK_STREAM)???
  • 你用什么参数调用listen?添加print(repr(host), repr(port)) 看看你得到了什么。
  • 例如,假设你调用了someobject.listen(('localhost', 80)),即你传递了一个元组为host,你可能会得到这样的错误。
  • 我打印出来了!主机是字符串'localhost',端口是int 1234
  • 我按照你说的更改了选项,但出现错误:“不支持协议”

标签: python string


【解决方案1】:

再次,我认为您对 socket.socket(...) 的选择不正确。如果您尝试创建 TCP 侦听器,则此方法有效

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('localhost',5555))
s.listen(5)

【讨论】:

  • 请注意,对于低端口范围 (
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
相关资源
最近更新 更多