【发布时间】:2019-10-11 12:57:26
【问题描述】:
我正在尝试在 Lua 客户端和 Python 服务器之间创建持久套接字连接。实际上是一个脚本,它会不断地用 keepalive 消息 ping 服务器
我当前的问题是套接字在每次连接后都会关闭,而无法重新打开它以进行传输。
Lua 客户端:
local HOST, PORT = "localhost", 9999
local socket = require('socket')
-- Create the client and initial connection
client, err = socket.connect(HOST, PORT)
client:setoption('keepalive', true)
-- Attempt to ping the server once a second
start = os.time()
while true do
now = os.time()
if os.difftime(now, start) >= 1 then
data = client:send("Hello World")
-- Receive data from the server and print out everything
s, status, partial = client:receive()
print(data, s, status, partial)
start = now
end
end
Python 服务器:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote".format(self.client_address[0]))
print(self.data)
print(self.client_address)
# Send back some arbitrary data
self.request.sendall(b'1')
if __name__ == '__main__':
HOST, PORT = "localhost", 9999
# Create a socketserver and serve is forever
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
server.serve_forever()
预期结果是每秒执行一次 keepalive ping,以确保客户端仍连接到服务器。
【问题讨论】:
标签: python python-3.x sockets lua luasocket