socket.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package gorilla
  2. import (
  3. "net"
  4. "net/http"
  5. "sync"
  6. "time"
  7. "github.com/kataras/neffos"
  8. gorilla "github.com/gorilla/websocket"
  9. )
  10. // Socket completes the `neffos.Socket` interface,
  11. // it describes the underline websocket connection.
  12. type Socket struct {
  13. UnderlyingConn *gorilla.Conn
  14. request *http.Request
  15. client bool
  16. mu sync.Mutex
  17. }
  18. func newSocket(underline *gorilla.Conn, request *http.Request, client bool) *Socket {
  19. return &Socket{
  20. UnderlyingConn: underline,
  21. request: request,
  22. client: client,
  23. }
  24. }
  25. // NetConn returns the underline net connection.
  26. func (s *Socket) NetConn() net.Conn {
  27. return s.UnderlyingConn.UnderlyingConn()
  28. }
  29. // Request returns the http request value.
  30. func (s *Socket) Request() *http.Request {
  31. return s.request
  32. }
  33. // ReadData reads binary or text messages from the remote connection.
  34. func (s *Socket) ReadData(timeout time.Duration) ([]byte, neffos.MessageType, error) {
  35. for {
  36. if timeout > 0 {
  37. s.UnderlyingConn.SetReadDeadline(time.Now().Add(timeout))
  38. }
  39. opCode, data, err := s.UnderlyingConn.ReadMessage()
  40. if err != nil {
  41. return nil, 0, err
  42. }
  43. if opCode != gorilla.BinaryMessage && opCode != gorilla.TextMessage {
  44. // if gorilla.IsUnexpectedCloseError(err, gorilla.CloseGoingAway) ...
  45. continue
  46. }
  47. return data, neffos.MessageType(opCode), err
  48. }
  49. }
  50. // WriteBinary sends a binary message to the remote connection.
  51. func (s *Socket) WriteBinary(body []byte, timeout time.Duration) error {
  52. return s.write(body, gorilla.BinaryMessage, timeout)
  53. }
  54. // WriteText sends a text message to the remote connection.
  55. func (s *Socket) WriteText(body []byte, timeout time.Duration) error {
  56. return s.write(body, gorilla.TextMessage, timeout)
  57. }
  58. func (s *Socket) write(body []byte, opCode int, timeout time.Duration) error {
  59. if timeout > 0 {
  60. s.UnderlyingConn.SetWriteDeadline(time.Now().Add(timeout))
  61. }
  62. s.mu.Lock()
  63. err := s.UnderlyingConn.WriteMessage(opCode, body)
  64. s.mu.Unlock()
  65. return err
  66. }