Exemple #1
0
func serve(id string, client io.ReadWriteCloser) {
	log.Printf("Client %q connected", id)
	defer log.Printf("Client %q disconnected", id)

	xport := fatchan.New(client, nil)
	login := make(chan Handshake)
	xport.ToChan(login)

	user := <-login
	log.Printf("Client %q registered as %q", id, user.User)
	if !addUser(user.User, user.Recv) {
		user.Recv <- packet.Packet{
			Chat: &packet.Chat{
				User:    "******",
				Message: "That username is already taken.",
			},
		}
		close(user.Recv)
		return
	}
	defer delUser(user.Recv)
	defer close(user.Recv)

	player := serverpkg.NewPlayer(id, user.User, user.Recv)
	defer player.Disconnected()

	for msg := range user.Send {
		if !serverpkg.Dispatch(player, msg) {
			return
		}
	}
}
Exemple #2
0
func serve(id string, client net.Conn) {
	log.Printf("[client:%s] connected", id)
	defer client.Close()
	defer log.Printf("[client:%s] disconnected", id)

	bufclient := bufio.NewWriter(client)
	encode, decode := gob.NewEncoder(bufclient), gob.NewDecoder(client)

	var handshake Handshake
	if err := decode.Decode(&handshake); err != nil {
		log.Printf("[client:%s] decoding handshake: %s", id, err)
		return
	}
	log.Printf("[client:%s] %#v", id, handshake)

	send := make(chan *packet.Packet)

	go serverEncode(id, bufclient, encode, client, send)

	defer close(send)
	if !addUser(send, handshake) {
		return
	}
	defer delUser(send)

	var flags uint32
	if handshake.Monkey {
		flags |= packet.FlagMonkey
	} else {
		flags |= packet.FlagSuit
	}

	// TODO: names
	player := serverpkg.NewPlayer(id, send, flags)
	defer player.Disconnected()

	var fastZero packet.Packet
	for {
		msg := new(packet.Packet)
		client.SetReadDeadline(time.Now().Add(2 * time.Minute))
		if err := decode.Decode(msg); err != nil {
			if err == io.EOF {
				return
			}

			log.Printf("[client:%s] decoding packet: %s", id, err)
			continue
		}
		if *msg != fastZero && !serverpkg.Dispatch(player, msg) {
			return
		}
	}
}