main.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "git.swzry.com/zry/SatorIPC/golang/sipc_conn"
  6. "io"
  7. "net"
  8. "os"
  9. "os/signal"
  10. "sync"
  11. "time"
  12. )
  13. func main() {
  14. var isServer bool
  15. var pipename string
  16. flag.BoolVar(&isServer, "s", false, "Server mode")
  17. flag.StringVar(&pipename, "p", sipc_conn.GeneratePath(), "Pipe name")
  18. flag.Parse()
  19. if isServer {
  20. fmt.Println("Listen Pipe Name:", pipename)
  21. c := make(chan os.Signal, 1)
  22. signal.Notify(c, os.Interrupt, os.Kill)
  23. server, err := sipc_conn.NewServer(pipename, false)
  24. if err != nil {
  25. fmt.Println("CreateServerError:", err.Error())
  26. return
  27. }
  28. server.SetConnErrorHandler(func(err error) {
  29. fmt.Println("[Conn] Failed Handling Connection:", err.Error())
  30. })
  31. server.SetConnHandler(handleConnection)
  32. err = server.Start()
  33. if err != nil {
  34. fmt.Println("StartServerError:", err.Error())
  35. return
  36. }
  37. s := <-c
  38. err = server.Stop()
  39. if err != nil {
  40. fmt.Println("StopServerError:", err.Error())
  41. }
  42. fmt.Println("Program Quit By Signal:", s)
  43. } else {
  44. fmt.Println("Dial Pipe Name:", pipename)
  45. conn, err := sipc_conn.Dial(pipename, 1*time.Second)
  46. if err != nil {
  47. fmt.Println("DialError:", err.Error())
  48. return
  49. }
  50. handleConnection(conn)
  51. fmt.Println("Program End By Connection Lost.")
  52. }
  53. }
  54. func handleConnection(netconn net.Conn) {
  55. wg := sync.WaitGroup{}
  56. wg.Add(2)
  57. go func() {
  58. outs := os.Stdout
  59. n, err := io.Copy(outs, netconn)
  60. if err != nil {
  61. fmt.Println("Recv IO Error:", err.Error())
  62. }
  63. fmt.Printf("%d byte(s) recieved.\n", n)
  64. wg.Done()
  65. }()
  66. go func() {
  67. ins := os.Stdin
  68. n, err := io.Copy(netconn, ins)
  69. if err != nil {
  70. fmt.Println("Transmit IO Error:", err.Error())
  71. }
  72. fmt.Printf("%d byte(s) transmitted.\n", n)
  73. wg.Done()
  74. }()
  75. wg.Wait()
  76. }