websocket 增加多分组 fork https://github.com/olahol/melody
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
1.9 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package melody
  2. import (
  3. "github.com/gorilla/websocket"
  4. "time"
  5. )
  6. // A melody session.
  7. type Session struct {
  8. conn *websocket.Conn
  9. output chan *envelope
  10. config *Config
  11. }
  12. func newSession(config *Config, conn *websocket.Conn) *Session {
  13. return &Session{
  14. conn: conn,
  15. output: make(chan *envelope, config.MessageBufferSize),
  16. config: config,
  17. }
  18. }
  19. func (s *Session) writeMessage(message *envelope) {
  20. s.output <- message
  21. }
  22. func (s *Session) writeRaw(message *envelope) error {
  23. s.conn.SetWriteDeadline(time.Now().Add(s.config.WriteWait))
  24. return s.conn.WriteMessage(message.t, message.msg)
  25. }
  26. func (s *Session) close() {
  27. s.writeRaw(&envelope{t: websocket.CloseMessage, msg: []byte{}})
  28. }
  29. func (s *Session) ping() {
  30. s.writeMessage(&envelope{t: websocket.PingMessage, msg: []byte{}})
  31. }
  32. func (s *Session) writePump(errorHandler handleErrorFunc) {
  33. defer s.conn.Close()
  34. ticker := time.NewTicker(s.config.PingPeriod)
  35. defer ticker.Stop()
  36. for {
  37. select {
  38. case msg, ok := <-s.output:
  39. if !ok {
  40. s.close()
  41. return
  42. }
  43. if err := s.writeRaw(msg); err != nil {
  44. go errorHandler(s, err)
  45. return
  46. }
  47. case <-ticker.C:
  48. s.ping()
  49. }
  50. }
  51. }
  52. func (s *Session) readPump(messageHandler handleMessageFunc, errorHandler handleErrorFunc) {
  53. defer s.conn.Close()
  54. s.conn.SetReadLimit(s.config.MaxMessageSize)
  55. s.conn.SetReadDeadline(time.Now().Add(s.config.PongWait))
  56. s.conn.SetPongHandler(func(string) error {
  57. s.conn.SetReadDeadline(time.Now().Add(s.config.PongWait))
  58. return nil
  59. })
  60. for {
  61. _, message, err := s.conn.ReadMessage()
  62. if err != nil {
  63. go errorHandler(s, err)
  64. break
  65. }
  66. go messageHandler(s, message)
  67. }
  68. }
  69. // Write message to session.
  70. func (s *Session) Write(msg []byte) {
  71. s.writeMessage(&envelope{t: websocket.TextMessage, msg: msg})
  72. }
  73. // Close session.
  74. func (s *Session) Close() {
  75. s.writeMessage(&envelope{t: websocket.CloseMessage, msg: []byte{}})
  76. }