title: Write to Client UDP Socket in Go
body: <p>I'm looking for a good solution for a client/server communication with UDP sockets in Go language.</p>
  
  <p>The examples I found on the Internet show me how to send data to the server, but they do not teach how to send them back to the client.</p>
  
  <p>To demonstrate, my program does the following:</p>
  
  <p>My client program creates a socket on the 4444 port, like this:</p>
  
  <pre><code>con, err := net.Dial("udp", "127.0.0.1:4444")
  </code></pre>
  
  <p>I sent a string and the local address to the server, so it could print the string and send an OK message. I am using gob for this:</p>
  
  <pre><code>enc := gob.NewEncoder(con)
  enc.Encode(Data{"test", con.LocalAddr().String()})
  </code></pre>
  
  <p>My Data struct looks like this:</p>
  
  <pre><code>type Data struct{
      Msg string
      Addr string
  }
  </code></pre>
  
  <p>My server listens to the 4444 port and decodes the Gob correctly, but how can I send the OK message back? I'm using the client address to do so (on the server .go file):</p>
  
  <pre><code>con, err := net.Dial("udp", data.Addr)
  </code></pre>
  
  <p>Then, I get an error code:</p>
  
  <pre><code>write udp 127.0.0.1:35290: connection refused
  </code></pre>
  
  <p>When the client tries to connect to the Server's port 4444, the client creates a port with a random number (in this case, 35290) so they can communicate. I know I shouldn't be passing the client's address to the server, but conn.RemoteAddress() does not work. A solution that discovers the client's address would be most appreciated.</p>
  
  <p>Obs.: I know there is ReadFromUDP, so I can read the package. Should I read it, discover the client's address, and send the data to Gob so it can decode it?</p>