Example #1
0
// 连接初始化,绑定节点与连接,默认key为节点ip
func (self *TP) sInitConn(conn *Connect, remoteAddr string) (nodeuid string, usable bool) {
	read_len, err := conn.Read(conn.Buffer)
	if err != nil || read_len == 0 {
		return
	}
	// 解包
	conn.TmpBuffer = append(conn.TmpBuffer, conn.Buffer[:read_len]...)
	dataSlice := make([][]byte, 10)
	dataSlice, conn.TmpBuffer = self.Unpack(conn.TmpBuffer)

	for i, data := range dataSlice {
		debug.Println("Debug: 收到数据-第1批-解码前: ", string(data))

		d := new(NetData)
		json.Unmarshal(data, d)
		// 修复缺失请求方地址的请求
		if d.From == "" {
			d.From = remoteAddr // 或可为:strings.Split(remoteAddr, ":")[0]
		}

		if i == 0 {
			debug.Printf("Debug: 收到数据-第1条-NetData: %+v", d)

			// 检查连接权限
			if !self.checkRights(d, remoteAddr) {
				return
			}

			nodeuid = d.From

			// 添加连接到节点池
			self.connPool[nodeuid] = conn

			// 判断是否为短链接
			if d.Operation != IDENTITY {
				conn.Short = true
			} else {
				log.Printf(" *     —— 客户端 %v (%v) 连接成功 ——", nodeuid, remoteAddr)
			}

			// 标记连接已经正式生效可用
			conn.Usable = true
		}
		// 添加到读取缓存
		self.apiReadChan <- d
	}
	return nodeuid, true
}
Example #2
0
// 通信数据编码与发送
func (self *TP) send(data *NetData) {
	if data.From == "" {
		data.From = self.uid
	}

	d, err := json.Marshal(*data)
	if err != nil {
		debug.Println("Debug: 发送数据-编码出错", err)
		return
	}
	conn := self.getConn(data.To)
	if conn == nil {
		debug.Printf("Debug: 发送数据-连接已断开: %+v", data)
		return
	}
	// 封包
	end := self.Packet(d)
	// 发送
	conn.Write(end)
	debug.Printf("Debug: 发送数据-成功: %+v", data)
}