Exemplo n.º 1
0
func (n *Node) Handle() {
	defer n.conn.Close()

	cb := func(reader *bufio.Reader, err error) {
		if err != nil {
			nodes.DelPeer(n.Name)
			glog.Infof("Node die, name=%s", n.Name)
			return
		}

		// Check size
		sizeBuf, err := reader.Peek(4)
		if err != nil {
			return
		}
		var size uint32
		binary.Read(bytes.NewBuffer(sizeBuf), binary.BigEndian, &size)
		if _, err = reader.Peek(4 + int(size)); err != nil {
			return
		}

		// Read Body
		packBuf := make([]byte, 4+int(size))
		reader.Read(packBuf)
		bodyBuf := packBuf[4:]

		// Parse packet id from body
		var packetId uint16
		binary.Read(bytes.NewBuffer(bodyBuf), binary.BigEndian, &packetId)
		handlerFunc, ok := handlers[packetId]
		if !ok {
			glog.Errorf("packet id error, pid=%d", packetId)
			return
		}

		// Decode message from body
		handler := handlerFunc()
		msgBuf := bytes.NewBuffer(bodyBuf[2:])
		err = gob.NewDecoder(msgBuf).Decode(handler)
		if err != nil {
			glog.Errorf("packet decode error, pid=%d err=%s", packetId, err.Error())
			return
		}

		glog.Infof("packet is %v", handler)

		handler.Handle(n)
	}

	myNet.RecvLoop(n.conn, cb)
}
Exemplo n.º 2
0
func recv() {
	cb := func(reader *bufio.Reader, err error) {
		if err != nil {
			fmt.Println("Recv err", err.Error())
			os.Exit(2)
		}

		packBuf := make([]byte, 512)
		reader.Read(packBuf)
		fmt.Printf("%s say: %s\n", conn.RemoteAddr(), string(packBuf))
	}

	go clawNet.RecvLoop(conn, cb)
}
Exemplo n.º 3
0
func ConnHandle(conn net.Conn) {
	sessionIdGenerator++
	client := &Client{sessionIdGenerator, conn}
	clients.AddPeer(client.session, client)

	cb := func(reader *bufio.Reader, err error) {
		if err != nil {
			defer conn.Close()
			clients.DelPeer(client.session)
			glog.Infof("Gate lose peer, session=%d", client.session)
		}

		if regReader != nil {
			regReader(client.session, reader, err)
		}
	}

	go clawNet.RecvLoop(conn, cb)
}