Exemplo n.º 1
0
func (c *Connection) write() {
	curNumMsg := 0
	lastTime := time.Now()

	for {
		select {
		case <-c.disconnectChan:
			return
		case msg, ok := <-c.outgoing:
			if !ok {
				return
			}
			data := msg.ConvertToBytes()
			// c.conn.SetWriteDeadline(time.Now().Add(70 * time.Second))
			_, err := c.writer.Write(data)
			if err != nil {
				log.ErrorErrorf(err, "Can't write all data to connection")
				c.Disconnect()
				return
			}
			c.writer.Flush()

			// log.Debugf("finished write message(%d)", msg.sessionId)

			c.mtx.Lock()
			c.lastUseTime = time.Now()
			c.mtx.Unlock()

			// limit the write speed
			curNumMsg++
			now := time.Now()
			d := now.Sub(lastTime)
			if d.Seconds() >= 1 {
				lastTime = now
				curNumMsg = 0
			}
			if curNumMsg > c.speedLimit {
				time.Sleep(d)
			}
		}
	}
}
Exemplo n.º 2
0
func (c *Connection) read() {
	curNumMsg := 0
	lastTime := time.Now()
	for {
		// c.conn.SetReadDeadline(time.Now().Add(70 * time.Second))
		msg, err := readMsgFromReader(c.reader)
		if err != nil {
			log.ErrorErrorf(err, "Can't read Msg from %s", c.addr)
			close(c.incoming)
			c.Disconnect()
			return
		}

		c.mtx.Lock()
		c.lastUseTime = time.Now()
		c.mtx.Unlock()

		select {
		case <-c.disconnectChan:
			close(c.incoming)
			c.Disconnect()
			return
		case c.incoming <- msg:
		}

		// limit the read speed
		curNumMsg++
		now := time.Now()
		d := now.Sub(lastTime)
		if d.Seconds() >= 1 {
			lastTime = now
			curNumMsg = 0
		}
		if curNumMsg > c.speedLimit {
			time.Sleep(d)
		}
	}
}