|
@@ -15,9 +15,11 @@
|
|
|
package main
|
|
|
|
|
|
import (
|
|
|
+ "bufio"
|
|
|
"encoding/json"
|
|
|
"flag"
|
|
|
"fmt"
|
|
|
+ "io"
|
|
|
"log"
|
|
|
"net"
|
|
|
)
|
|
@@ -31,21 +33,42 @@ type Message struct {
|
|
|
func main() {
|
|
|
flag.Parse()
|
|
|
|
|
|
- // TODO: Create a net.Listener listening from the address in the "listen" flag.
|
|
|
+ // Create a net.Listener listening from the address in the "listen" flag.
|
|
|
+ l, err := net.Listen("tcp4", *listenAddr)
|
|
|
+ if err != nil {
|
|
|
+ log.Fatal(err)
|
|
|
+ }
|
|
|
|
|
|
for {
|
|
|
- // TODO: Accept a new connection from the listener.
|
|
|
+ // Accept a new connection from the listener.
|
|
|
+ c, err := l.Accept()
|
|
|
+ if err != nil {
|
|
|
+ log.Fatal(err)
|
|
|
+ }
|
|
|
+
|
|
|
go serve(c)
|
|
|
}
|
|
|
}
|
|
|
|
|
|
func serve(c net.Conn) {
|
|
|
- // TODO: Use defer to Close the connection when this function returns.
|
|
|
+ // Use defer to Close the connection when this function returns.
|
|
|
+ defer c.Close()
|
|
|
|
|
|
- // TODO: Create a new json.Decoder reading from the connection.
|
|
|
+ // Create a new json.Decoder reading from the connection.
|
|
|
+ d := json.NewDecoder(bufio.NewReader(c)) // NewDecoder(c) would loop on EOF
|
|
|
for {
|
|
|
- // TODO: Create an empty message.
|
|
|
- // TODO: Decode a new message into the variable you just created.
|
|
|
- // TODO: Print the message to the standard output.
|
|
|
+ // Create an empty message.
|
|
|
+ m := Message{}
|
|
|
+ // Decode a new message into the variable you just created.
|
|
|
+ err := d.Decode(&m)
|
|
|
+ if err == io.EOF {
|
|
|
+ break
|
|
|
+ }
|
|
|
+ if err != nil {
|
|
|
+ log.Fatal(err)
|
|
|
+ }
|
|
|
+ // Print the message to the standard output.
|
|
|
+ fmt.Println(m)
|
|
|
}
|
|
|
+ log.Println("Closing connection on EOF.")
|
|
|
}
|