我看到你正在使用self
,所以你在里面class
。
为什么不在self.client_socket = client_socket
构造函数中使用?
# update your constructor with self.client_socket
def __init__(client_socket, **other_args_of_yours):
# use this object variable when you activate key listener
self.client_socket = client_socket
或添加self.client_socket = client_socket
方法handle_keyboard_events()
:
def handle_keyboard_events(self, client_socket):
self.client_socket = client_socket # <----- update
keyboard_listener = keyboard.Listener(
on_press=self.on_key_press,
on_release=self.on_key_release
)
keyboard_listener.start()
self.client_socket
在press
和release
方法中使用
def on_key_press(self, key):
key_press_command = KeyPress(key)
self.send_message(key_press_command, True, self.client_socket) # <--- update
def on_key_release(self, key):
key_release_command = KeyRelease(key)
self.send_message(key_release_command, True, self.client_socket) # <--- update
或者
如果你真的想传递client_socket
给你的press
andrelease
方法,你可以试试这个:
def handle_keyboard_events(self, client_socket):
# use lambda to pass the client socket
# with this method, after you get the `key` you can pass additional params to on_press and on_release
keyboard_listener = keyboard.Listener(
on_press=lambda key: self.on_key_press(key, client_socket), # <--- client socket passed
on_release=lambda key: self.on_key_release(key, client_socket) # <--- client socket passed
)
keyboard_listener.start()
# add client socket as new arg
def on_key_press(self, key, client_socket):
key_press_command = KeyPress(key)
self.send_message(key_press_command, True, client_socket) # from params
# add client socket as new arg
def on_key_release(self, key, client_socket):
key_release_command = KeyRelease(key)
self.send_message(key_release_command, True, client_socket) # from params
你准备好了。