catch socket timeout error

时间:2018-02-21 03:06:53

标签: python-3.x sockets error-handling timeout

i want to catch socket.timeout error, here is my code:

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)

but when i running that code. i got this error:

Server Listening...
Traceback (most recent call last):
  File "C:\Users\astend\Desktop\TA\20180220 - Gabungan Gui  - v.1\Socket\terima2.py", line 13, in <module>
    (server, (ip,port)) = serverSocket.accept()
  File "C:\Users\astend\AppData\Local\Programs\Python\Python36\lib\socket.py", line 205, in accept
    fd, addr = self._accept()
socket.timeout: timed out

What key point am I missing here?

1 个答案:

答案 0 :(得分:0)

您需要在accept()区块内执行try

或者不要在侦听套接字上设置超时,将其设置在接受的套接字上。