| 398 | } |
| 399 | |
| 400 | void ConsoleServer::execute_message_handlers(bool sync) |
| 401 | { |
| 402 | bool locked = true; |
| 403 | if (sync) |
| 404 | _input_semaphore.wait(); |
| 405 | else |
| 406 | locked = _input_semaphore.try_wait(); |
| 407 | |
| 408 | if (!locked) |
| 409 | return; |
| 410 | |
| 411 | Buffer *temp = _input_read; |
| 412 | _input_read = _input_write; |
| 413 | _input_write = temp; |
| 414 | _handlers_semaphore.post(); |
| 415 | |
| 416 | // Do not execute message handlers at exit, because when _thread_exit is |
| 417 | // set by shutdown(), handlers may reference stale objects. |
| 418 | if (_thread_exit) |
| 419 | return; |
| 420 | |
| 421 | FileBuffer fb(*_input_read); |
| 422 | BinaryReader br(fb); |
| 423 | while (!fb.end_of_file()) { |
| 424 | // Read client, message size and message. |
| 425 | u32 client_id; |
| 426 | u32 msg_len; |
| 427 | br.read(client_id); |
| 428 | br.read(msg_len); |
| 429 | const char *msg = array::begin(*_input_read) + fb.position(); |
| 430 | br.skip(msg_len); |
| 431 | |
| 432 | if (msg_len > 0) { |
| 433 | // Process the message if any. |
| 434 | JsonObject obj(default_allocator()); |
| 435 | sjson::parse(obj, msg); |
| 436 | |
| 437 | if (!json_object::has(obj, "type")) { |
| 438 | error(client_id, "Missing command type"); |
| 439 | continue; |
| 440 | } |
| 441 | |
| 442 | // Find handler for the message type. |
| 443 | TempAllocator256 ta; |
| 444 | DynamicString command_type(ta); |
| 445 | sjson::parse_string(command_type, obj["type"]); |
| 446 | |
| 447 | CommandData cmd; |
| 448 | cmd.message_function = NULL; |
| 449 | cmd.user_data = NULL; |
| 450 | cmd = hash_map::get(_messages |
| 451 | , command_type.to_string_id() |
| 452 | , cmd |
| 453 | ); |
| 454 | if (!cmd.message_function) { |
| 455 | TempAllocator256 err_ta; |
| 456 | StringStream err_msg(err_ta); |
| 457 | err_msg << "Unknown command type '" << command_type.c_str() << "'"; |