session.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package TcpServerLib
  2. import (
  3. "net"
  4. )
  5. // Session holds info about connection
  6. type Session struct {
  7. conn net.Conn
  8. Server *server
  9. Device_Sn string
  10. Verify_num int
  11. }
  12. func (session *Session) handleTcpRead() {
  13. session.Server.onNewClientCallback(session)
  14. //var startRecvPos int16
  15. //var result int
  16. recviveBuff := make([]byte, MAX_RECEIVE_BUFFER_SIZE)
  17. for {
  18. recvBytes, err := session.conn.Read(recviveBuff)
  19. if err != nil {
  20. /*logs.PrintlnError("TCP - handleTcpRead",err)
  21. continue;*/
  22. //logs.PrintlnError("TCP - handleTcpRead",err)
  23. session.closeProcess(NET_CLOSE_REMOTE)
  24. return
  25. }
  26. //logs.Println("recvBytes:",recvBytes)
  27. session.Server.onNewMessage(session, recviveBuff[:recvBytes])
  28. //
  29. //if recvBytes < HEADER_SIZE {
  30. // session.closeProcess(NET_CLOSE_RECV_TOO_SMALL_RECV_DATA)
  31. // return
  32. //}
  33. //
  34. //readAbleByte := int16(startRecvPos) + int16(recvBytes)
  35. //startRecvPos, result = session.makePacket(readAbleByte, recviveBuff)
  36. //if result != NET_ERROR_NONE {
  37. // session.closeProcess(result)
  38. // return
  39. //}
  40. }
  41. }
  42. func (session *Session) closeProcess(reason int) {
  43. session.conn.Close()
  44. session.Server.onClientConnectionClosed(session, reason)
  45. }
  46. func (session *Session) makePacket(readAbleByte int16, recviveBuff []byte) (int16, int) {
  47. var startRecvPos int16 = 0
  48. var readPos int16
  49. for {
  50. if readAbleByte < HEADER_SIZE {
  51. break
  52. }
  53. requireDataSize := packetTotalSize(recviveBuff[readPos:])
  54. if requireDataSize > readAbleByte {
  55. break
  56. }
  57. if requireDataSize > MAX_PACKET_SIZE {
  58. return startRecvPos, NET_ERROR_RECV_MAKE_PACKET_TOO_LARGE_PACKET_SIZE
  59. }
  60. ltvPacket := recviveBuff[readPos:(readPos + requireDataSize)]
  61. readPos += requireDataSize
  62. readAbleByte -= requireDataSize
  63. session.Server.onNewMessage(session, ltvPacket)
  64. }
  65. if readAbleByte > 0 {
  66. copy(recviveBuff, recviveBuff[readPos:(readPos+readAbleByte)])
  67. }
  68. startRecvPos = readAbleByte
  69. return startRecvPos, NET_ERROR_NONE
  70. }
  71. // Send text message to client
  72. func (session *Session) Send(message string) error {
  73. _, err := session.conn.Write([]byte(message))
  74. return err
  75. }
  76. // Send bytes to client
  77. func (session *Session) SendBytes(b []byte) error {
  78. _, err := session.conn.Write(b)
  79. return err
  80. }
  81. func (session *Session) Conn() net.Conn {
  82. return session.conn
  83. }
  84. func (session *Session) Close() error {
  85. return session.conn.Close()
  86. }