另客网go项目公用的代码库

context_websocket.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package linker
  2. import (
  3. "context"
  4. "hash/crc32"
  5. "runtime"
  6. "strconv"
  7. "github.com/gorilla/websocket"
  8. "github.com/wpajqz/linker/codec"
  9. )
  10. var _ Context = new(ContextWebsocket)
  11. type ContextWebsocket struct {
  12. defaultContext
  13. Conn *webSocketConn
  14. }
  15. func NewContextWebsocket(conn *webSocketConn, OperateType uint32, Sequence int64, Header, Body []byte, config Config) *ContextWebsocket {
  16. return &ContextWebsocket{
  17. defaultContext: defaultContext{
  18. Context: context.Background(),
  19. operateType: OperateType,
  20. sequence: Sequence,
  21. config: config,
  22. Request: struct{ Header, Body []byte }{Header: Header, Body: Body},
  23. body: Body,
  24. },
  25. Conn: conn,
  26. }
  27. }
  28. // 响应请求成功的数据包
  29. func (c *ContextWebsocket) Success(body interface{}) {
  30. r, err := codec.NewCoder(c.config.ContentType)
  31. if err != nil {
  32. panic(err)
  33. }
  34. data, err := r.Encoder(body)
  35. if err != nil {
  36. panic(err)
  37. }
  38. p, err := NewPacket(c.operateType, c.sequence, c.Response.Header, data, c.config.PluginForPacketSender)
  39. if err != nil {
  40. panic(err)
  41. }
  42. c.Conn.WriteMessage(websocket.BinaryMessage, p.Bytes())
  43. runtime.Goexit()
  44. }
  45. // 响应请求失败的数据包
  46. func (c *ContextWebsocket) Error(code int, message string) {
  47. c.SetResponseProperty("code", strconv.Itoa(code))
  48. c.SetResponseProperty("message", message)
  49. p, err := NewPacket(c.operateType, c.sequence, c.Response.Header, nil, c.config.PluginForPacketSender)
  50. if err != nil {
  51. panic(err)
  52. }
  53. c.Conn.WriteMessage(websocket.BinaryMessage, p.Bytes())
  54. runtime.Goexit()
  55. }
  56. // 向客户端发送数据
  57. func (c *ContextWebsocket) Write(operator string, body interface{}) (int, error) {
  58. r, err := codec.NewCoder(c.config.ContentType)
  59. if err != nil {
  60. return 0, err
  61. }
  62. data, err := r.Encoder(body)
  63. if err != nil {
  64. return 0, err
  65. }
  66. p, err := NewPacket(crc32.ChecksumIEEE([]byte(operator)), 0, c.Response.Header, data, c.config.PluginForPacketSender)
  67. if err != nil {
  68. panic(err)
  69. }
  70. return 0, c.Conn.WriteMessage(websocket.BinaryMessage, p.Bytes())
  71. }
  72. func (c *ContextWebsocket) LocalAddr() string {
  73. return c.Conn.LocalAddr().String()
  74. }
  75. func (c *ContextWebsocket) RemoteAddr() string {
  76. return c.Conn.RemoteAddr().String()
  77. }