doc.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Package ws implements a client and server for the WebSocket protocol as
  3. specified in RFC 6455.
  4. The main purpose of this package is to provide simple low-level API for
  5. efficient work with protocol.
  6. Overview.
  7. Upgrade to WebSocket (or WebSocket handshake) can be done in two ways.
  8. The first way is to use `net/http` server:
  9. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  10. conn, _, _, err := ws.UpgradeHTTP(r, w)
  11. })
  12. The second and much more efficient way is so-called "zero-copy upgrade". It
  13. avoids redundant allocations and copying of not used headers or other request
  14. data. User decides by himself which data should be copied.
  15. ln, err := net.Listen("tcp", ":8080")
  16. if err != nil {
  17. // handle error
  18. }
  19. conn, err := ln.Accept()
  20. if err != nil {
  21. // handle error
  22. }
  23. handshake, err := ws.Upgrade(conn)
  24. if err != nil {
  25. // handle error
  26. }
  27. For customization details see `ws.Upgrader` documentation.
  28. After WebSocket handshake you can work with connection in multiple ways.
  29. That is, `ws` does not force the only one way of how to work with WebSocket:
  30. header, err := ws.ReadHeader(conn)
  31. if err != nil {
  32. // handle err
  33. }
  34. buf := make([]byte, header.Length)
  35. _, err := io.ReadFull(conn, buf)
  36. if err != nil {
  37. // handle err
  38. }
  39. resp := ws.NewBinaryFrame([]byte("hello, world!"))
  40. if err := ws.WriteFrame(conn, frame); err != nil {
  41. // handle err
  42. }
  43. As you can see, it stream friendly:
  44. const N = 42
  45. ws.WriteHeader(ws.Header{
  46. Fin: true,
  47. Length: N,
  48. OpCode: ws.OpBinary,
  49. })
  50. io.CopyN(conn, rand.Reader, N)
  51. Or:
  52. header, err := ws.ReadHeader(conn)
  53. if err != nil {
  54. // handle err
  55. }
  56. io.CopyN(ioutil.Discard, conn, header.Length)
  57. For more info see the documentation.
  58. */
  59. package ws