Channel client

In order to find an exported channel, the client must import it. This is created using Import which takes a protocol and a network service address of “host:port”. This is then used to import a network channel by name and bind it to a local channel. Note that channel variables are references, so you do not need to pass their addresses to functions that change them.

The following client gets two channels to and from the echo server, and then writes and reads ten messages:

  1. /* EchoClient
  2. */
  3. package main
  4. import (
  5. "fmt"
  6. "old/netchan"
  7. "os"
  8. )
  9. func main() {
  10. if len(os.Args) != 2 {
  11. fmt.Println("Usage: ", os.Args[0], "host:port")
  12. os.Exit(1)
  13. }
  14. service := os.Args[1]
  15. importer, err := netchan.Import("tcp", service)
  16. checkError(err)
  17. fmt.Println("Got importer")
  18. echoIn := make(chan string)
  19. importer.Import("echo-in", echoIn, netchan.Recv, 1)
  20. fmt.Println("Imported in")
  21. echoOut := make(chan string)
  22. importer.Import("echo-out", echoOut, netchan.Send, 1)
  23. fmt.Println("Imported out")
  24. for n := 0; n < 10; n++ {
  25. echoOut <- "hello "
  26. s, ok := <-echoIn
  27. if !ok {
  28. fmt.Println("Read failure")
  29. break
  30. }
  31. fmt.Println(s, n)
  32. }
  33. close(echoOut)
  34. os.Exit(0)
  35. }
  36. func checkError(err error) {
  37. if err != nil {
  38. fmt.Println("Fatal error ", err.Error())
  39. os.Exit(1)
  40. }
  41. }