【问题标题】:Simple Python socket server does not run on macOS简单的 Python 套接字服务器不在 macOS 上运行
【发布时间】:2020-10-27 05:47:48
【问题描述】:

我创建了一个小的 Python 套接字服务器代码,当我尝试与客户端连接时,我得到:

OSError: [Errno 57] Socket is not connected

我不确定为什么会这样,即使服务器正在运行。

这是我的代码: server.py

# Imports
import socket


# Variables
ip_address = ''
ip_port = 10000
max_connections = 5

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# Code
s.bind((socket.gethostname(), ip_port))
s.listen(max_connections)

while True:
    clientsocket, address = s.accept()
    print(f"{address} connected!")
    clientsocket.send(bytes("quit", txt))

client.py

# Imports
import socket


# Variables
ip_address = ''
ip_port = 10000

txt = 'utf-8'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
msg = s.recv(1024)


# Code
"""Connect to the server"""
s.connect((ip_address, ip_port))


while True:
    var = msg.decode(txt)
    print(var)
    if var == "quit":
        break

【问题讨论】:

    标签: python python-3.x sockets networking


    【解决方案1】:

    我已经更改了您代码中的一些要点,并且它在这里正常工作。我已将 ip_address 设置为 127.0.0.1,担心 MacOS 的安全问题。我还删除了发送函数的第二个参数。

    server.py

    # Imports
    import socket
    
    # Variables
    ip_address = '127.0.0.1'
    ip_port = 10000
    max_connections = 5
    
    txt = 'utf-8'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Code
    s.bind((ip_address, ip_port))
    s.listen(max_connections)
    
    while True:
        clientsocket, address = s.accept()
        print("{} connected!", address)
        clientsocket.send(b"quit")
    

    在客户端,recv 在套接字连接之前被调用。

    client.py

    # Imports
    import socket
    
    # Variables
    ip_address = '127.0.0.1'
    ip_port = 10000
    
    txt = 'utf-8'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Code
    """Connect to the server"""
    s.connect((ip_address, ip_port))
    
    while True:
        msg = s.recv(1024)
        var = msg.decode(txt)
        if var == "quit":
            break
    

    【讨论】:

    • 新的 IP 地址有效,但如果是通过网络呢?
    • 服务器可能在 127.0.0.1 监听,客户端通过网络连接到服务器 ip。代码在你的机器上运行了吗?
    • 我通常必须将 ip_address 设置为 0.0.0.0 才能列出网络上的流量。不要忘记防火墙和路由器之类的东西
    • 哦,是的,对于实际应用来说,这是必须的。
    • 抱歉,回复晚了,但效果很好。再次感谢:)
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    相关资源
    最近更新 更多