繁体   English   中英

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

[英]Persistent socket connection in Lua/Python

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

我最终找到了解决方案。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM