예제 #1
0
func (self *Server) Start(connString string) {

	listener, err := net.Listen("tcp", connString)

	if err != nil {
		log.Println(err)
	}

	self.listener = listener

	log.Println("Server start")

	// filling the tokens
	for i := 0; i < MAX_SESSIONS; i++ {
		self.generateToken()
	}

	for {
		conn, err := self.listener.Accept()

		if err != nil {
			log.Println(err)
			return
		}

		log.Printf("A new connection [ %+v ]  %s\n", conn, conn.RemoteAddr().String())

		self.takeToken()
		self.pending <- conn
	}
}
예제 #2
0
func (self *Session) Read() {

	for {
		if packet, err := self.packetReader.ReadAPacket(); err == nil {
			log.Printf("放入进入信息通道%+v", packet)
			self.incoming <- *packet
		} else {
			log.Println("Read error:", err)
			self.quit()
			return
		}
	}
}
예제 #3
0
func (self *Server) join(conn net.Conn) {

	session := CreateSession(self, conn)
	id := TypeSessionID(uniq.GetUniq())
	session.SetID(id)
	self.sessions[id] = session
	log.Printf("join session:%+v", session)
	go func() {
		<-session.quiting
		delete(self.sessions, session.GetID())
		self.quiting <- session.GetConn()
	}()

}
예제 #4
0
func (r *PacketReader) ReadAPacket() (packet *Packet, err error) {

	packet = NewPacket()

	//check packet hat
	hasHat, err := r.checkPacketHat()
	if !hasHat {
		return nil, ErrInvalidPacketHat
	}

	//check packet type
	packetType, err := r.readPacketType()

	if err != nil {
		return nil, err
	}

	packet.SetType(packetType)

	//check packet length
	packetLength, err := r.readPacketLength()

	if err != nil {
		return nil, err
	}

	if packetLength > maxPacketLength {
		return nil, ErrInvalidPacketLength
	}

	//alloc packet data buffer
	packetData := make([]byte, packetLength)
	//read packet data
	err = r.readPacketData(packetData)
	if err != nil {
		return nil, err
	}
	packet.SetData(packetData)
	log.Printf("收到的数据包-->%+v", packet)
	err = r.checkDataSumIEEE(packetData)
	if err != nil {
		log.Println("read errors: %s", err)
		return nil, err
	}
	return packet, nil
}
예제 #5
0
func CreateSession(server *Server, conn net.Conn) *Session {
	packetReader := NewPacketReader(conn)
	packetWriter := NewPacketWriter(conn)

	Session := &Session{
		conn:         conn,
		incoming:     make(chan Packet),
		outgoing:     make(chan Packet),
		quiting:      make(chan byte),
		packetReader: packetReader,
		packetWriter: packetWriter,
		server:       server,
	}
	log.Printf("create session [ %+v ]\n", Session)
	Session.Listen(server)
	return Session
}