首页 > 解决方案 > 错误问题:fd, addr = self._accept()

问题描述

我试图在 python 中建立服务器和客户端之间的连接。但程序只是运行直到等待连接。程序无法读取地址。

import socket
import sys

host = ''
port = 5131

s = socket.socket()

s.bind((host,port))

s.listen(1)
print('listening')


while 1:

    print('Waiting for a connection......')
    c, addr = s.accept()
    print('Connection established with', addr)


c.close()

结果是这样的:

listening
Waiting for a connection......
Traceback (most recent call last):
  File "/Users/muhrisdham/Downloads/tugas/01.tugas_tcp_server.py", line 32, in <module>
    c, addr = s.accept()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 212, in accept
    fd, addr = self._accept()
KeyboardInterrupt

请原谅我的英语,谢谢你

标签: pythonpython-3.xtcp

解决方案


我假设您在程序卡住时必须按下 ctrl+C。因此键盘中断。

你写的是server。在您的情况下,它旨在阻止s.accept()呼叫,直到与它正在侦听的地址(0.0.0.0:5131)建立新连接。建立新连接后,您将处理该连接(以某种方式)。

现在你剩下要做的就是实现客户端

查看本教程:https ://pymotw.com/2/socket/tcp.html


推荐阅读