gproc_comm_send.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2018 gf Author(https://github.com/gogf/gf). 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. "errors"
  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: gPROC_COMM_DEFAULT_GRUOP_NAME,
  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. err = json.Unmarshal(result, response)
  44. if err == nil {
  45. if response.Code != 1 {
  46. err = errors.New(response.Message)
  47. }
  48. }
  49. }
  50. // EOF is not really an error.
  51. if err == io.EOF {
  52. err = nil
  53. }
  54. return err
  55. }