【问题标题】:Persistent socket connection in Lua/PythonLua/Python 中的持久套接字连接
【发布时间】: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


    【解决方案1】:

    我最终找到了解决方案。

    问题似乎出在 Python 中的 socketserver 库上。我将它切换到原始套接字,事情开始按照我想要的方式工作。从那里我创建了线程来处理后台的来回处理

    Python 服务器:

    import socket, threading
    
    HOST, PORT = "localhost", 9999
    
    # Ensures the connection is still active
    def keepalive(conn, addr):
        print("Client connected")
        with conn:
            conn.settimeout(3)
            while True:
                try:
                    data = conn.recv(1024)
                    if not data: break
                    message = data.split(b',')
                    if message[0] == b'ping':
                        conn.sendall(b'pong' + b'\n')
                except Exception as e:
                    break
            print("Client disconnected")
    
    # Listens for connections to the server and starts a new keepalive thread
    def listenForConnections():
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.bind((HOST, PORT))
            while True:
                sock.listen()
                conn, addr = sock.accept()
                t = threading.Thread(target=keepalive, args=(conn, addr))
                t.start()
    
    if __name__ == '__main__':
        # Starts up the socket server
        SERVER = threading.Thread(target=listenForConnections)
        SERVER.start()
    
        # Run whatever code after this
    

    Lua 客户端在这种情况下没有改变

    【讨论】:

    • 感谢您提出(然后回答)我的问题@ThomasR!我是 Python 新手,各种 socketserver 类确实可以开箱即用——如果你想要的话。但我没有,我的用例和你的很像,这无疑让我朝着正确的方向开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多