Пример #1
0
// Handles incoming requests.
func handleRequest(newCon netCon) {
	for {
		msg, err := common.ReadMsg(newCon.connection)
		if err != nil {
			if err == io.EOF {
				// Close the connection when you're done with it.
				removeConn(newCon.connection)
				newCon.connection.Close()
				return
			}
			log.Println(err)
			return
		}
		if newCon.isHandShakeing {
			fmt.Printf("Message Received: %s\n", msg)
			broadcast(newCon, msg)
		} else {
			var y map[string]interface{}
			json.Unmarshal([]byte(msg), &y)
			for n, v := range y {
				if n == "username" {
					for i := range netCons {
						if netCons[i] == newCon {
							netCons[i].isHandShakeing = true
							netCons[i].username = v.(string)
							newCon = netCons[i]
						}
					}
				}
			}
			fmt.Printf("Handshake success: %s\n", newCon.username)
			broadcast(newCon, newCon.username+" has join now")
		}
	}
}
Пример #2
0
func printOutput(conn *net.TCPConn) {
	for {

		msg, err := common.ReadMsg(conn)
		// Receiving EOF means that the connection has been closed
		if err == io.EOF {
			// Close conn and exit
			conn.Close()
			fmt.Println("Connection Closed. Bye bye.")
			os.Exit(0)
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(msg)
	}
}