websocket.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package net
  2. import (
  3. "errors"
  4. "net"
  5. "net/http"
  6. "time"
  7. "golang.org/x/net/websocket"
  8. )
  9. var ErrWebsocketListenerClosed = errors.New("websocket listener closed")
  10. const (
  11. FrpWebsocketPath = "/~!frp"
  12. )
  13. type WebsocketListener struct {
  14. ln net.Listener
  15. acceptCh chan net.Conn
  16. server *http.Server
  17. }
  18. // NewWebsocketListener to handle websocket connections
  19. // ln: tcp listener for websocket connections
  20. func NewWebsocketListener(ln net.Listener) (wl *WebsocketListener) {
  21. wl = &WebsocketListener{
  22. acceptCh: make(chan net.Conn),
  23. }
  24. muxer := http.NewServeMux()
  25. muxer.Handle(FrpWebsocketPath, websocket.Handler(func(c *websocket.Conn) {
  26. notifyCh := make(chan struct{})
  27. conn := WrapCloseNotifyConn(c, func() {
  28. close(notifyCh)
  29. })
  30. wl.acceptCh <- conn
  31. <-notifyCh
  32. }))
  33. wl.server = &http.Server{
  34. Addr: ln.Addr().String(),
  35. Handler: muxer,
  36. ReadHeaderTimeout: 60 * time.Second,
  37. }
  38. go func() {
  39. _ = wl.server.Serve(ln)
  40. }()
  41. return
  42. }
  43. func (p *WebsocketListener) Accept() (net.Conn, error) {
  44. c, ok := <-p.acceptCh
  45. if !ok {
  46. return nil, ErrWebsocketListenerClosed
  47. }
  48. return c, nil
  49. }
  50. func (p *WebsocketListener) Close() error {
  51. return p.server.Close()
  52. }
  53. func (p *WebsocketListener) Addr() net.Addr {
  54. return p.ln.Addr()
  55. }