Ejemplo n.º 1
0
//disconnect user by deleting him/her from list
func disconnect(msg Message) {
	mutex.Lock()
	delete(usersIPsMap, msg.Username)
	delete(usersConnectionsMap, msg.Username)
	mutex.Unlock()
	newUserList, _ := utils.GetFromMap(usersIPsMap)

	updateUserListChan <- newUserList
	updateTextChan <- msg.Username + " left the chat"
}
Ejemplo n.º 2
0
// adds a peer to everyone list
func addPeer(msg Message) {

	mutex.Lock()
	usersIPsMap[msg.Username] = msg.IP
	conn := createConnection(msg.IP)
	usersConnectionsMap[msg.Username] = conn
	mutex.Unlock()

	userNames, _ := utils.GetFromMap(usersIPsMap)

	updateUserListChan <- userNames
	updateTextChan <- msg.Username + " just joined the chat (from IP: " + msg.IP + ")"
}
Ejemplo n.º 3
0
// connects with everyone in the chat.
// The Message passed in contains a list of users and ips
func connectToPeers(msg Message) {
	for index, ip := range msg.IPs {
		conn := createConnection(ip)

		mutex.Lock()
		usersIPsMap[msg.Usernames[index]] = ip
		usersConnectionsMap[msg.Usernames[index]] = conn
		mutex.Unlock()
	}
	users, _ := utils.GetFromMap(usersIPsMap)

	updateUserListChan <- users

	addMessage := Message{"ADD", MyName, utils.GetMyIP(), "", make([]string, 0), make([]string, 0)}
	addMessage.Send()
}
Ejemplo n.º 4
0
// handle a connection with a new peer
func handleConnect(msg Message, conn net.Conn) bool {

	log.Println("handleConnect")

	Users, IPs := utils.GetFromMap(usersIPsMap)
	Users = append(Users, MyName)      //add my name to the list
	IPs = append(IPs, utils.GetMyIP()) //add my ip to the list
	response := Message{"LIST", "", "", "", Users, IPs}
	if _, usernameTaken := usersIPsMap[msg.Username]; usernameTaken {
		response.MSG = "Username already taken, choose another one that is not in the list"
		response.Send()
		return false
	}

	mutex.Lock()
	usersIPsMap[msg.Username] = msg.IP
	usersConnectionsMap[msg.Username] = conn
	mutex.Unlock()

	log.Println(usersConnectionsMap)
	response.SendPrivToUser(msg.Username, updateTextChan)
	return true
}