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.

297 lines
8.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 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
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package melody
  2. import (
  3. "errors"
  4. "net/http"
  5. "sync"
  6. "github.com/gorilla/websocket"
  7. )
  8. // Close codes defined in RFC 6455, section 11.7.
  9. // Duplicate of codes from gorilla/websocket for convenience.
  10. const (
  11. CloseNormalClosure = 1000
  12. CloseGoingAway = 1001
  13. CloseProtocolError = 1002
  14. CloseUnsupportedData = 1003
  15. CloseNoStatusReceived = 1005
  16. CloseAbnormalClosure = 1006
  17. CloseInvalidFramePayloadData = 1007
  18. ClosePolicyViolation = 1008
  19. CloseMessageTooBig = 1009
  20. CloseMandatoryExtension = 1010
  21. CloseInternalServerErr = 1011
  22. CloseServiceRestart = 1012
  23. CloseTryAgainLater = 1013
  24. CloseTLSHandshake = 1015
  25. )
  26. // Duplicate of codes from gorilla/websocket for convenience.
  27. var validReceivedCloseCodes = map[int]bool{
  28. // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number
  29. CloseNormalClosure: true,
  30. CloseGoingAway: true,
  31. CloseProtocolError: true,
  32. CloseUnsupportedData: true,
  33. CloseNoStatusReceived: false,
  34. CloseAbnormalClosure: false,
  35. CloseInvalidFramePayloadData: true,
  36. ClosePolicyViolation: true,
  37. CloseMessageTooBig: true,
  38. CloseMandatoryExtension: true,
  39. CloseInternalServerErr: true,
  40. CloseServiceRestart: true,
  41. CloseTryAgainLater: true,
  42. CloseTLSHandshake: false,
  43. }
  44. type handleMessageFunc func(*Session, []byte)
  45. type handleErrorFunc func(*Session, error)
  46. type handleCloseFunc func(*Session, int, string) error
  47. type handleSessionFunc func(*Session)
  48. type filterFunc func(*Session) bool
  49. // Melody implements a websocket manager.
  50. type Melody struct {
  51. Config *Config
  52. Upgrader *websocket.Upgrader
  53. messageHandler handleMessageFunc
  54. messageHandlerBinary handleMessageFunc
  55. messageSentHandler handleMessageFunc
  56. messageSentHandlerBinary handleMessageFunc
  57. errorHandler handleErrorFunc
  58. closeHandler handleCloseFunc
  59. connectHandler handleSessionFunc
  60. disconnectHandler handleSessionFunc
  61. pongHandler handleSessionFunc
  62. hub *hub
  63. }
  64. // New creates a new melody instance with default Upgrader and Config.
  65. func New() *Melody {
  66. upgrader := &websocket.Upgrader{
  67. ReadBufferSize: 1024,
  68. WriteBufferSize: 1024,
  69. }
  70. hub := newHub()
  71. go hub.run()
  72. return &Melody{
  73. Config: newConfig(),
  74. Upgrader: upgrader,
  75. messageHandler: func(*Session, []byte) {},
  76. messageHandlerBinary: func(*Session, []byte) {},
  77. messageSentHandler: func(*Session, []byte) {},
  78. messageSentHandlerBinary: func(*Session, []byte) {},
  79. errorHandler: func(*Session, error) {},
  80. closeHandler: func(*Session, int, string) error { return nil },
  81. connectHandler: func(*Session) {},
  82. disconnectHandler: func(*Session) {},
  83. pongHandler: func(*Session) {},
  84. hub: hub,
  85. }
  86. }
  87. // HandleConnect fires fn when a session connects.
  88. func (m *Melody) HandleConnect(fn func(*Session)) {
  89. m.connectHandler = fn
  90. }
  91. // HandleDisconnect fires fn when a session disconnects.
  92. func (m *Melody) HandleDisconnect(fn func(*Session)) {
  93. m.disconnectHandler = fn
  94. }
  95. // HandlePong fires fn when a pong is received from a session.
  96. func (m *Melody) HandlePong(fn func(*Session)) {
  97. m.pongHandler = fn
  98. }
  99. // HandleMessage fires fn when a text message comes in.
  100. func (m *Melody) HandleMessage(fn func(*Session, []byte)) {
  101. m.messageHandler = fn
  102. }
  103. // HandleMessageBinary fires fn when a binary message comes in.
  104. func (m *Melody) HandleMessageBinary(fn func(*Session, []byte)) {
  105. m.messageHandlerBinary = fn
  106. }
  107. // HandleSentMessage fires fn when a text message is successfully sent.
  108. func (m *Melody) HandleSentMessage(fn func(*Session, []byte)) {
  109. m.messageSentHandler = fn
  110. }
  111. // HandleSentMessageBinary fires fn when a binary message is successfully sent.
  112. func (m *Melody) HandleSentMessageBinary(fn func(*Session, []byte)) {
  113. m.messageSentHandler = fn
  114. }
  115. // HandleError fires fn when a session has an error.
  116. func (m *Melody) HandleError(fn func(*Session, error)) {
  117. m.errorHandler = fn
  118. }
  119. // HandleClose sets the handler for close messages received from the session.
  120. // The code argument to h is the received close code or CloseNoStatusReceived
  121. // if the close message is empty. The default close handler sends a close frame
  122. // back to the session.
  123. //
  124. // The application must read the connection to process close messages as
  125. // described in the section on Control Frames above.
  126. //
  127. // The connection read methods return a CloseError when a close frame is
  128. // received. Most applications should handle close messages as part of their
  129. // normal error handling. Applications should only set a close handler when the
  130. // application must perform some action before sending a close frame back to
  131. // the session.
  132. func (m *Melody) HandleClose(fn func(*Session, int, string) error) {
  133. if fn != nil {
  134. m.closeHandler = fn
  135. }
  136. }
  137. // HandleRequest upgrades http requests to websocket connections and dispatches them to be handled by the melody instance.
  138. func (m *Melody) HandleRequest(w http.ResponseWriter, r *http.Request) error {
  139. return m.HandleRequestWithKeys(w, r, nil)
  140. }
  141. // HandleRequestWithKeys does the same as HandleRequest but populates session.Keys with keys.
  142. func (m *Melody) HandleRequestWithKeys(w http.ResponseWriter, r *http.Request, keys map[string]interface{}) error {
  143. if m.hub.closed() {
  144. return errors.New("Melody instance is closed.")
  145. }
  146. conn, err := m.Upgrader.Upgrade(w, r, nil)
  147. if err != nil {
  148. return err
  149. }
  150. session := &Session{
  151. Request: r,
  152. Keys: keys,
  153. conn: conn,
  154. output: make(chan *envelope, m.Config.MessageBufferSize),
  155. melody: m,
  156. open: true,
  157. rwmutex: &sync.RWMutex{},
  158. }
  159. m.hub.register <- session
  160. m.connectHandler(session)
  161. go session.writePump()
  162. session.readPump()
  163. if !m.hub.closed() {
  164. m.hub.unregister <- session
  165. }
  166. session.close()
  167. m.disconnectHandler(session)
  168. return nil
  169. }
  170. // Broadcast broadcasts a text message to all sessions.
  171. func (m *Melody) Broadcast(msg []byte) error {
  172. if m.hub.closed() {
  173. return errors.New("Melody instance is closed.")
  174. }
  175. message := &envelope{t: websocket.TextMessage, msg: msg}
  176. m.hub.broadcast <- message
  177. return nil
  178. }
  179. // BroadcastFilter broadcasts a text message to all sessions that fn returns true for.
  180. func (m *Melody) BroadcastFilter(msg []byte, fn func(*Session) bool) error {
  181. if m.hub.closed() {
  182. return errors.New("Melody instance is closed.")
  183. }
  184. message := &envelope{t: websocket.TextMessage, msg: msg, filter: fn}
  185. m.hub.broadcast <- message
  186. return nil
  187. }
  188. // BroadcastOthers broadcasts a text message to all sessions except session s.
  189. func (m *Melody) BroadcastOthers(msg []byte, s *Session) error {
  190. return m.BroadcastFilter(msg, func(q *Session) bool {
  191. return s != q
  192. })
  193. }
  194. // BroadcastBinary broadcasts a binary message to all sessions.
  195. func (m *Melody) BroadcastBinary(msg []byte) error {
  196. if m.hub.closed() {
  197. return errors.New("Melody instance is closed.")
  198. }
  199. message := &envelope{t: websocket.BinaryMessage, msg: msg}
  200. m.hub.broadcast <- message
  201. return nil
  202. }
  203. // BroadcastBinaryFilter broadcasts a binary message to all sessions that fn returns true for.
  204. func (m *Melody) BroadcastBinaryFilter(msg []byte, fn func(*Session) bool) error {
  205. if m.hub.closed() {
  206. return errors.New("Melody instance is closed.")
  207. }
  208. message := &envelope{t: websocket.BinaryMessage, msg: msg, filter: fn}
  209. m.hub.broadcast <- message
  210. return nil
  211. }
  212. // BroadcastBinaryOthers broadcasts a binary message to all sessions except session s.
  213. func (m *Melody) BroadcastBinaryOthers(msg []byte, s *Session) error {
  214. return m.BroadcastBinaryFilter(msg, func(q *Session) bool {
  215. return s != q
  216. })
  217. }
  218. // Close closes the melody instance and all connected sessions.
  219. func (m *Melody) Close() error {
  220. if m.hub.closed() {
  221. return errors.New("Melody instance is already closed.")
  222. }
  223. m.hub.exit <- &envelope{t: websocket.CloseMessage, msg: []byte{}}
  224. return nil
  225. }
  226. // CloseWithMsg closes the melody instance with the given close payload and all connected sessions.
  227. // Use the FormatCloseMessage function to format a proper close message payload.
  228. func (m *Melody) CloseWithMsg(msg []byte) error {
  229. if m.hub.closed() {
  230. return errors.New("Melody instance is already closed.")
  231. }
  232. m.hub.exit <- &envelope{t: websocket.CloseMessage, msg: msg}
  233. return nil
  234. }
  235. // Len return the number of connected sessions.
  236. func (m *Melody) Len() int {
  237. return m.hub.len()
  238. }
  239. // FormatCloseMessage formats closeCode and text as a WebSocket close message.
  240. func FormatCloseMessage(closeCode int, text string) []byte {
  241. return websocket.FormatCloseMessage(closeCode, text)
  242. }