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.

92 lines
1.9 KiB

10 years ago
  1. package melody
  2. import (
  3. "github.com/gorilla/websocket"
  4. "net/http"
  5. )
  6. type handleMessageFunc func(*Session, []byte)
  7. type handleErrorFunc func(*Session, error)
  8. type handleSessionFunc func(*Session)
  9. type filterFunc func(*Session) bool
  10. type Melody struct {
  11. Config *Config
  12. Upgrader *websocket.Upgrader
  13. MessageHandler handleMessageFunc
  14. ErrorHandler handleErrorFunc
  15. ConnectHandler handleSessionFunc
  16. DisconnectHandler handleSessionFunc
  17. hub *hub
  18. }
  19. func Default() *Melody {
  20. upgrader := &websocket.Upgrader{
  21. ReadBufferSize: 1024,
  22. WriteBufferSize: 1024,
  23. }
  24. hub := newHub()
  25. go hub.run()
  26. return &Melody{
  27. Config: newConfig(),
  28. Upgrader: upgrader,
  29. MessageHandler: func(*Session, []byte) {},
  30. ErrorHandler: func(*Session, error) {},
  31. ConnectHandler: func(*Session) {},
  32. DisconnectHandler: func(*Session) {},
  33. hub: hub,
  34. }
  35. }
  36. func (m *Melody) HandleConnect(fn handleSessionFunc) {
  37. m.ConnectHandler = fn
  38. }
  39. func (m *Melody) HandleDisconnect(fn handleSessionFunc) {
  40. m.DisconnectHandler = fn
  41. }
  42. func (m *Melody) HandleMessage(fn handleMessageFunc) {
  43. m.MessageHandler = fn
  44. }
  45. func (m *Melody) HandleError(fn handleErrorFunc) {
  46. m.ErrorHandler = fn
  47. }
  48. func (m *Melody) HandleRequest(w http.ResponseWriter, r *http.Request) error {
  49. conn, err := m.Upgrader.Upgrade(w, r, nil)
  50. if err != nil {
  51. return err
  52. }
  53. session := newSession(m.Config, conn)
  54. m.hub.register <- session
  55. go m.ConnectHandler(session)
  56. go session.writePump(m.ErrorHandler)
  57. session.readPump(m.MessageHandler, m.ErrorHandler)
  58. m.hub.unregister <- session
  59. go m.DisconnectHandler(session)
  60. return nil
  61. }
  62. func (m *Melody) Broadcast(msg []byte) {
  63. message := &envelope{t: websocket.TextMessage, msg: msg}
  64. m.hub.broadcast <- message
  65. }
  66. func (m *Melody) BroadcastFilter(fn filterFunc, msg []byte) {
  67. message := &envelope{t: websocket.TextMessage, msg: msg, filter: fn}
  68. m.hub.broadcast <- message
  69. }