event_handler_map = { MessageType.login: login, MessageType.send_message: send_message, MessageType.register: register, MessageType.resolve_friend_request: resolve_friend_request, MessageType.client_echo: client_echo, MessageType.add_friend: add_friend, MessageType.join_room: join_room, MessageType.create_room: create_room, MessageType.query_room_users: query_room_users, MessageType.bad: bad, } def handle_event(sc, event_type, parameters): event_handler_map[event_type].run(sc, parameters) 这段代码什么意思
时间: 2023-07-14 11:12:28 浏览: 482
这段代码定义了一个事件处理器映射表 `event_handler_map`,将每个事件的类型(`MessageType`)与对应的处理函数关联起来。然后定义了一个 `handle_event` 函数,该函数接收三个参数:`sc` 表示当前的客户端连接,`event_type` 表示事件的类型,`parameters` 表示事件的参数。`handle_event` 函数根据事件类型从 `event_handler_map` 中取出对应的处理函数,并调用该函数来处理事件。这样可以方便地扩展系统,增加新的事件类型时只需要添加对应的处理函数即可。
相关问题
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class); if (annotation != null) { if (this.isRepeatSubmit(request, annotation)) { AjaxResult ajaxResult = AjaxResult.error(annotation.message()); ServletUtils.renderString(response, JSON.toJSONString(ajaxResult)); return false; } } } boolean flag = false; TokenService tokenService = SpringUtils.getBean(TokenService.class); LoginAppUser loginUser = tokenService.getLoginUser(request); if (loginUser != null && loginUser.getGuest() != null && loginUser.getGuest().getGuestNum() != null) { tokenService.verifyToken(loginUser); String guestNum = loginUser.getGuest().getGuestNum(); HttpSession httpSession = request.getSession(); RedisCache redisUtil = SpringUtils.getBean(RedisCache.class); Guest guest = redisUtil.getCacheMapValue(RedisConstants.GUEST_MAP, guestNum); SysGuest sysGuest = JSON.parseObject(JSON.toJSONString(guest), SysGuest.class); if (sysGuest == null) { flag = false; httpSession.removeAttribute(Constants.SERVER_TYPE_APP); } else { if (httpSession.getAttribute(Constants.SERVER_TYPE_APP) == null) { httpSession.setAttribute(Constants.SERVER_TYPE_APP , sysGuest); } return true; } } 优化这段代码
首先,可以将该方法拆分成两个方法,一个处理重复提交的逻辑,一个处理登录用户的逻辑,以提高代码可读性和可维护性。
处理重复提交的逻辑可以改为使用注解方式,遍历所有的参数,判断是否存在 @Token 注解,如果存在则验证 token 是否一致。
处理登录用户的逻辑可以简化代码,将获取当前登录用户和验证 token 的逻辑移动到 TokenService 中,简化该方法代码。
重构后的代码如下所示:
```
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Token annotation = method.getAnnotation(Token.class);
if (annotation != null) {
if (!tokenService.verifyToken(request)) {
AjaxResult ajaxResult = AjaxResult.error(annotation.message());
ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
return false;
}
}
}
if (tokenService.checkLogin(request)) {
HttpSession session = request.getSession();
if (session.getAttribute(Constants.SERVER_TYPE_APP) == null) {
session.setAttribute(Constants.SERVER_TYPE_APP, tokenService.getLoginUser(request).getGuest());
}
return true;
} else {
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED.value(), "未登录或登录超时。")));
return false;
}
}
```
其中,`TokenService` 的实现中包括了 `verifyToken` 和 `checkLogin` 方法,分别用于验证 token 和检查当前用户是否已经登录。同时,重复提交的逻辑使用 `@Token` 注解进行处理。
class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, message): # 接收客户端请求 # self.accept() await self.channel_layer.group_add( "chat_group", self.channel_name, ) await self.accept() await self.send("连接") async def websocket_receive(self, message, ): await self.channel_layer.group_send( "chat_group", { "type": "chat_message", "message": message, }, ) await self.send("999999") print(message) await self.send("已收到") print("shoudao") check = message.get('check') print(check) file_data = message.get('file') print(file_data) await self.send('正在打开数据...') # df = pd.read_excel('received_file.xlsx',engine='openpyxl') df = pd.read_excel(file_data) def websocket_disconnect(self, message): print("断开连接") raise StopConsumer() socket.onmessage = function (event) { let tag = document.createElement("div") tag.innerText = event.data document.getElementById("message").appendChild(tag); console.log(tag) } def index(request): if request.method == "GET": return render(request, 'index.html') if request.method == "POST": file = request.FILES.get("file") check = request.POST.get('check') # main(file, check, 15) # 获取Channel层对象 channel_layer = get_channel_layer() # 发送消息到ChatConsumer的websocket_receive方法 async_to_sync(channel_layer.group_send)('chat_group', { 'type': 'websocket.receive', 'file': file, 'check': check, }) # main(file, check, 15) return render(request, 'index.html')前端弹窗中可以接收def websocket_connect的self.send但却接收不到 websocket_receive中的self.send内容,但websocket_receive中的print都可以正常运行,是怎么回事?且报 No handler for message type chat_message的错误
根据你提供的代码,我注意到在`websocket_receive`方法中你使用了`self.channel_layer.group_send()`方法发送消息给群组`chat_group`,但是前端无法接收到该消息。
这是因为`self.channel_layer.group_send()`方法发送的消息会被后台处理,而不会直接发送给前端。在`websocket_receive`方法中,你可以使用`self.send()`方法向客户端发送消息。但是请注意,`self.send()`方法应该在`self.channel_layer.group_send()`之前调用,以确保消息能够传递到前端。
以下是修正后的代码示例:
```python
class ChatConsumer(AsyncWebsocketConsumer):
async def websocket_connect(self, message):
await self.channel_layer.group_add("chat_group", self.channel_name)
await self.accept()
await self.send("连接")
async def websocket_receive(self, message):
await self.send("999999")
print(message)
await self.send("已收到")
print("shoudao")
check = message.get('check')
print(check)
file_data = message.get('file')
print(file_data)
await self.send('正在打开数据...')
# df = pd.read_excel('received_file.xlsx',engine='openpyxl')
df = pd.read_excel(file_data)
await self.send(df.to_dict()) # 将数据发送给前端
def websocket_disconnect(self, message):
print("断开连接")
raise StopConsumer()
```
在上述示例中,我将`df.to_dict()`作为数据通过`await self.send()`方法发送给前端。你可以根据需要修改发送的数据格式。
请确保前端代码能够正确处理接收到的消息,并在前端弹窗中显示数据。如果你仍然遇到`No handler for message type chat_message`错误,请确保在后台代码中正确定义了`chat_message`类型的消息处理方法。
阅读全文
相关推荐








Traceback (most recent call last): File "d:\pythonbaijiahao\baijiahao.py", line 82, in mianrun sub_element.click() File "D:\python3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 81, in click self._execute(Command.CLICK_ELEMENT) File "D:\python3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 710, in _execute return self._parent.execute(command, params) File "D:\python3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 425, in execute self.error_handler.check_response(response) File "D:\python3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element 管理商品 is not clickable at point (930, 347). Other element would receive the click: <svg viewBox="64 64 896 896" focusable="false" data-icon="vertical-align-top" width="1em" height="1em" fill="currentColor" aria-hidden="true">...</svg> (Session info: MicrosoftEdge=113.0.1774.42) Stacktrace:




Traceback (most recent call last): File "d:\pythonbaijiahao\baijiahao.py", line 63, in mianrun pagination_element.click() File "D:\python3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 81, in click self._execute(Command.CLICK_ELEMENT) File "D:\python3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 710, in _execute return self._parent.execute(command, params) File "D:\python3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 425, in execute self.error_handler.check_response(response) File "D:\python3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <button class="cheetah-pagination-item-link" type="button" tabindex="-1">...</button> is not clickable at point (953, 471). Other element would receive the click: ...




