gproc_comm_send.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gproc
  7. import (
  8. "github.com/gogf/gf/errors/gerror"
  9. "github.com/gogf/gf/internal/json"
  10. "github.com/gogf/gf/net/gtcp"
  11. "io"
  12. )
  13. // Send sends data to specified process of given pid.
  14. func Send(pid int, data []byte, group ...string) error {
  15. msg := MsgRequest{
  16. SendPid: Pid(),
  17. RecvPid: pid,
  18. Group: defaultGroupNameForProcComm,
  19. Data: data,
  20. }
  21. if len(group) > 0 {
  22. msg.Group = group[0]
  23. }
  24. msgBytes, err := json.Marshal(msg)
  25. if err != nil {
  26. return err
  27. }
  28. var conn *gtcp.PoolConn
  29. conn, err = getConnByPid(pid)
  30. if err != nil {
  31. return err
  32. }
  33. defer conn.Close()
  34. // Do the sending.
  35. var result []byte
  36. result, err = conn.SendRecvPkg(msgBytes, gtcp.PkgOption{
  37. Retry: gtcp.Retry{
  38. Count: 3,
  39. },
  40. })
  41. if len(result) > 0 {
  42. response := new(MsgResponse)
  43. if err = json.UnmarshalUseNumber(result, response); err == nil {
  44. if response.Code != 1 {
  45. err = gerror.New(response.Message)
  46. }
  47. }
  48. }
  49. // EOF is not really an error.
  50. if err == io.EOF {
  51. err = nil
  52. }
  53. return err
  54. }