Frederic G. MARAND 9 years ago
parent
commit
9f76221943
4 changed files with 16 additions and 2 deletions
  1. 1 1
      part8/main.go
  2. BIN
      part8/part8
  3. 15 1
      part9/main.go
  4. BIN
      part9/part9

+ 1 - 1
part8/main.go

@@ -100,7 +100,7 @@ func broadcast(m Message) {
 		// Hint: Select is your friend.
 		select {
 		case v <- m:
-			fmt.Printf("Sent %+v to %s", m, k)
+			fmt.Printf("Sent %+v to %s\n", m, k)
 		default:
 			fmt.Printf("Failed sending to %s\n", k)
 		}

BIN
part8/part8


+ 15 - 1
part9/main.go

@@ -118,6 +118,9 @@ func serve(c net.Conn) {
 		}
 
 		// TODO: If this message has seen before, ignore it.
+    if Seen(m.ID) {
+			return
+		}
 
 		fmt.Printf("%#v\n", m)
 		broadcast(m)
@@ -134,6 +137,8 @@ func readInput() {
 			Body: s.Text(),
 		}
 		// TODO: Mark the message ID as seen.
+		Seen(m.ID)
+
 		broadcast(m)
 	}
 	if err := s.Err(); err != nil {
@@ -170,11 +175,20 @@ func dial(addr string) {
 }
 
 // TODO: Create a new map of seen message IDs and a mutex to protect it.
+var seen_messages map[string]bool = make(map[string]bool)
+var seen_mutex sync.RWMutex
 
 // Seen returns true if the specified id has been seen before.
 // If not, it returns false and marks the given id as "seen".
 func Seen(id string) bool {
 	// TODO: Get a write lock on the seen message IDs map and unlock it at before returning.
+	defer seen_mutex.Unlock()
+	seen_mutex.Lock()
 	// TODO: Check if the id has been seen before and return that later.
-	// TODO: Mark the ID as seen in the map.
+	seen, ok := seen_messages[id]
+	if !ok {
+	  // TODO: Mark the ID as seen in the map.
+		seen_messages[id] = true
+	}
+	return seen
 }

BIN
part9/part9