Lua / Python中的持久套接字连接

时间:2019-05-25 00:40:53

标签: python python-3.x sockets lua luasocket

我正在尝试在Lua客户端和Python服务器之间创建持久的套接字连接。有效的脚本将不断向服务器发送保持活动消息

我当前的问题是每次连接后套接字都会关闭,而无法重新打开以进行传输。

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操作,以确保客户端仍连接到服务器。

1 个答案:

答案 0 :(得分:0)

我最终找到了解决方法。

问题似乎出在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客户端没有更改