chatsession.cpp
上传用户:zslianheng
上传日期:2013-04-03
资源大小:946k
文件大小:2k
源码类别:

Linux/Unix编程

开发平台:

Visual C++

  1. /***************************************************************************
  2.  *                                                                         *
  3.  *   This program is free software; you can redistribute it and/or modify  *
  4.  *   it under the terms of the GNU General Public License as published by  *
  5.  *   the Free Software Foundation; either version 2 of the License, or     *
  6.  *   (at your option) any later version.                                   *
  7.  *                                                                         *
  8.  *   copyright            : (C) 2002 by Zhang Yong                         *
  9.  *   email                : z-yong163@163.com                              *
  10.  ***************************************************************************/
  11. #include "chatsession.h"
  12. #include "packet.h"
  13. #include "lpc10codec.h"
  14. enum {
  15. CHAT_TEXT = 0x1000,
  16. CHAT_SPEECH_DATA,
  17. };
  18. ChatSession::ChatSession(TcpSessionBase *s)
  19. {
  20. tcp = s;
  21. listener = NULL;
  22. currentCodec = new Lpc10Codec;
  23. }
  24. ChatSession::~ChatSession()
  25. {
  26. if (currentCodec)
  27. delete currentCodec;
  28. if (tcp)
  29. tcp->destroy();
  30. }
  31. void ChatSession::sendChatText(const char *text)
  32. {
  33. OutPacket *out = tcp->createPacket(CHAT_TEXT);
  34. *out << text;
  35. tcp->sendPacket(out);
  36. }
  37. void ChatSession::sendSpeechData(const char *speech, int n)
  38. {
  39. char bits[4096];
  40. n = currentCodec->encode(speech, bits, n);
  41. OutPacket *out = tcp->createPacket(CHAT_SPEECH_DATA);
  42. out->writeData(bits, n);
  43. tcp->sendPacket(out);
  44. }
  45. void ChatSession::onChatText(InPacket &in)
  46. {
  47. const char *text;
  48. in >> text;
  49. if (listener)
  50. listener->onChatText(text);
  51. }
  52. void ChatSession::onSpeechData(InPacket &in)
  53. {
  54. int n;
  55. const char *bits = in.readData(n);
  56. char speech[4096];
  57. n = currentCodec->decode(bits, speech, n);
  58. if (listener)
  59. listener->onSpeechData(speech, n);
  60. }
  61. bool ChatSession::onPacketReceived(InPacket &in)
  62. {
  63. uint16 cmd = in.getCmd();
  64. switch (cmd) {
  65. case CHAT_TEXT:
  66. onChatText(in);
  67. break;
  68. case CHAT_SPEECH_DATA:
  69. onSpeechData(in);
  70. break;
  71. default:
  72. return false;
  73. }
  74. return true;
  75. }
  76. void ChatSession::onClose()
  77. {
  78. if (listener)
  79. listener->onClose();
  80. }