Python 3.5.2 Socket Keep-Alive

时间:2016-11-15 13:28:40

标签: python python-3.x sockets keep-alive

我正在尝试为我的套接字设置一个keep alive标志。我正在使用Python 3.5.2。这是代码:

ConnectionSocket, address = ServerSocket.accept()

ConnectionSocket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,1)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)

但我收到错误:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/QuizServer/QuizServer/MultiplexingServer.py", line 135, in <module>
    ConnectionSocket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,1)
AttributeError: type object 'socket' has no attribute 'SOL_SOCKET'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如何导入套接字库以及如何定义服务器套接字?您的代码段中缺少此内容。

import socket

ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerSocket.bind((socket.gethostname(), 4224))
ServerSocket.listen(0)
ConnectionSocket, address = ServerSocket.accept()


ConnectionSocket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,1)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
ConnectionSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)

此代码适用于Python3.5,不会产生任何错误。

哈努哈利