You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python socket调用bind()报错:AF_INET地址必须为元组而非字符串

错误原因

这个类型错误由server.bind()的传参格式不符合要求导致:

  • IPv4(AF_INET)模式下的socket调用bind(),必须传入(IP地址字符串, 端口号整数)格式的二元元组
  • 原代码里写的server.bind(("192.168.1.14, 4434"))把IP、逗号、端口全放在同一组引号内,括号里本质是单个字符串,不是方法要求的元组类型,因此直接触发报错。
修复方案

核心只需要调整bind()的传参格式,把IP和端口拆成元组的两个独立元素:将原代码第7行的

server.bind(("192.168.1.14, 4434"))

替换为

server.bind(("192.168.1.14", 4434))

注意端口号4434不要加引号,需要以整数类型传入。

修复后可直接运行的完整代码

以下版本同时补全了socket参数声明、客户端正常断开的判断逻辑,修正了原有拼写错误:

import socket
import select

# 服务端启动逻辑:绑定IP+端口,监听连接,打印启动提示
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("192.168.1.14", 4434))
server.listen(5)
inputs = [server]
print("booting up the server...")

# 向所有连接发送广播消息,排除non_receptors列表内的对象
def notify_all(msg, non_receptors):
    for connection in inputs:
        if connection not in non_receptors:
            connection.send(msg)

# 新客户端连接时发送欢迎信息,展示当前在线用户
def greet(client):
    names = [n.getpeername() for n in inputs if n is not client and n is not server]
    greetMsg = "hello user! \n users online:" + str(names)
    client.send(greetMsg.encode())

while inputs:
    readables, _, _ = select.select(inputs, [], [])
    for i in readables:
        if i is server:
            client, address = server.accept()
            inputs.append(client)
            print("connected to new client")
            greet(client)
            notify_all(f"client {address} entered".encode(), [server, client])

        else:
            try:
                data = i.recv(1024)
                if not data:
                    raise ConnectionResetError("Client closed connection")
                notify_all(f"{i.getpeername()}>>>{data.decode()}".encode(), [server, i])

            except Exception as e:
                print(e)
                inputs.remove(i)
                print(f"client {i.getpeername()} BYE")

内容的提问来源于stack exchange,提问作者itay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 15:48:21