catch插座超时错误



我想catch socket.TimeOut错误,这是我的代码:

import socket
import sys
from time import sleep
print("Server Listening...")
IPparse = "localhost"
Portparse = 4444
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (IPparse, Portparse)
serverSocket.settimeout(5)
serverSocket.bind(server_address)
serverSocket.listen(2)
(server, (ip,port)) = serverSocket.accept()
try:
    data = server.recv(16).decode()
    if data == "Hello":
        print("Hallo Bro")
except socket.timeout as e:
    print ("Timeout is over")
    print (e)

但是当我运行该代码时。我有一个错误:

Server Listening...
Traceback (most recent call last):
  File "C:UsersastendDesktopTA20180220 - Gabungan Gui  - v.1Socketterima2.py", line 13, in <module>
    (server, (ip,port)) = serverSocket.accept()
  File "C:UsersastendAppDataLocalProgramsPythonPython36libsocket.py", line 205, in accept
    fd, addr = self._accept()
socket.timeout: timed out

我在这里缺少什么关键点?

您需要在try块内进行accept()

否则不要在收听套接字上设置超时,将其设置在接受的插座上。

相关内容

  • 没有找到相关文章

最新更新