title: Synchronize reads and writes to TCP socket
body: <p>I'm trying to communicate with a TCP server which responds to messages:</p>
  
  <pre><code>package main
  
  import (
      "net"
      "log"
  )
  
  func handleErr(err error) {
      if err != nil {
          log.Fatal(err)
      }
  }
  
  func main() {
  
      // connect
      host := "1.2.3.4:5678"
      conn, err := net.Dial("tcp", host)
      handleErr(err)
      defer conn.Close()
  
      // write to socket
      message := "Test\n"
      conn.Write([]byte(message))
  
      // read from socket
      // (assume response is 'Test\n')
      reply := make([]byte, 1024)
      conn.Read(reply)
      log.Println(string(reply))
  
  }
  </code></pre>
  
  <p>What I'm trying to accomplish is to send a message to the socket-server on the other end, wait for a response and then process it. I seem to be having trouble with properly syncing these write/read operation to be timed correctly - right now the read action seems to block the write; I'm assuming this happens due to the async nature of Go. What's an idiomatic way to do this? Is it goroutines? A continuous <code>for { .. }</code> loop for the reader? A <code>sync.Wait</code> mechanism? Help is appreciated. thanks.</p>