Channel server

In order to make a channel visible to clients, you need to export it. This is done by creating an exporter using NewExporter with no parameters. The server then calls ListenAndServe to listen and handle responses. This takes two parameters, the first being the underlying transport mechanism such as “tcp” and the second being the network listening address (usually just a port number.

For each channel, the server creates a normal local channel and then calls Export to bind this to the network channel. At the time of export, the direction of communication must be specified. Clients search for channels by name, which is a string. This is specified to the exporter.

The server then uses the local channels in the normal way, reading or writing on them. We illustrate with an “echo” server which reads lines and sends them back. It needs two channels for this. The channel that the client writes to we name “echo-out”. On the server side this is a read channel. Similarly, the channel that the client reads from we call “echo-in”, which is a write channel to the server.

The server program is

  1. /* EchoServer
  2. */
  3. package main
  4. import (
  5. "fmt"
  6. "os"
  7. "old/netchan"
  8. )
  9. func main() {
  10. // exporter, err := netchan.NewExporter("tcp", ":2345")
  11. exporter := netchan.NewExporter()
  12. err := exporter.ListenAndServe("tcp", ":2345")
  13. checkError(err)
  14. echoIn := make(chan string)
  15. echoOut := make(chan string)
  16. exporter.Export("echo-in", echoIn, netchan.Send)
  17. exporter.Export("echo-out", echoOut, netchan.Recv)
  18. for {
  19. fmt.Println("Getting from echoOut")
  20. s, ok := <-echoOut
  21. if !ok {
  22. fmt.Printf("Read from channel failed")
  23. os.Exit(1)
  24. }
  25. fmt.Println("received", s)
  26. fmt.Println("Sending back to echoIn")
  27. echoIn <- s
  28. fmt.Println("Sent to echoIn")
  29. }
  30. }
  31. func checkError(err error) {
  32. if err != nil {
  33. fmt.Println("Fatal error ", err.Error())
  34. os.Exit(1)
  35. }
  36. }

Note: at the time of writing, the server will sometimes fail with an error message “netchan export: error encoding client response”. This is logged as Issue 1805**