当前位置: 首页>>代码示例>>Golang>>正文


Golang bencode-go.Marshal函数代码示例

本文整理汇总了Golang中github.com/jackpal/bencode-go.Marshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Marshal函数的具体用法?Golang Marshal怎么用?Golang Marshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Marshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: RegisterControlPeer

// RegisterControlPeer - This method register control peer on a Bootstrap node
func (dht *DHTClient) RegisterControlPeer() {
	for len(dht.ID) != 36 {
		time.Sleep(1 * time.Second)
	}
	var req DHTMessage
	var err error
	req.ID = dht.ID
	req.Query = "0"
	req.Command = DhtCmdRegProxy
	req.Arguments = fmt.Sprintf("%d", dht.P2PPort)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		return
	}
	// TODO: Optimize types here
	msg := b.String()
	for _, conn := range dht.Connection {
		if dht.Shutdown {
			continue
		}
		_, err = conn.Write([]byte(msg))
		if err != nil {
			Log(Error, "Failed to send packet: %v", err)
			conn.Close()
			return
		}
	}
}
开发者ID:subutai-io,项目名称:p2p,代码行数:30,代码来源:dht.go

示例2: RequestControlPeer

// RequestControlPeer - This method request a new control peer for particular host
func (dht *DHTClient) RequestControlPeer(id string, omit []*net.UDPAddr) {
	var req DHTMessage
	var err error
	req.ID = dht.ID
	req.Query = ""
	// Collect list of failed forwarders
	for _, fwd := range omit {
		req.Query += fwd.String() + "|"
	}
	req.Command = DhtCmdProxy
	req.Arguments = id
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		return
	}
	msg := b.String()
	// TODO: Move sending to a separate method
	for _, conn := range dht.Connection {
		if dht.Shutdown {
			continue
		}
		_, err = conn.Write([]byte(msg))
		if err != nil {
			Log(Error, "Failed to send packet: %v", err)
			conn.Close()
			return
		}
	}
}
开发者ID:subutai-io,项目名称:p2p,代码行数:31,代码来源:dht.go

示例3: Handshake

// Handshake performs data exchange between DHT client and server
func (dht *DHTClient) Handshake(conn *net.UDPConn) error {
	// Handshake
	var req DHTMessage
	req.ID = "0"
	req.Query = PacketVersion
	req.Command = DhtCmdConn
	// TODO: rename Port to something more clear
	req.Arguments = fmt.Sprintf("%d", dht.P2PPort)
	req.Payload = dht.NetworkHash
	for _, ip := range dht.IPList {
		req.Arguments = req.Arguments + "|" + ip.String()
	}
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		conn.Close()
		return err
	}
	// TODO: Optimize types here
	msg := b.String()
	if dht.Shutdown {
		return nil
	}
	_, err := conn.Write([]byte(msg))
	if err != nil {
		Log(Error, "Failed to send packet: %v", err)
		conn.Close()
		return err
	}
	return nil
}
开发者ID:subutai-io,项目名称:p2p,代码行数:32,代码来源:dht.go

示例4: Bencode

// Encode to Bencode, but only encode non-default values.
func (m *MetaInfo) Bencode(w io.Writer) (err error) {
	var mi map[string]interface{} = map[string]interface{}{}
	id := m.Info.toMap()
	if len(id) > 0 {
		mi["info"] = id
	}
	// Do not encode InfoHash. Clients are supposed to calculate it themselves.
	if m.Announce != "" {
		mi["announce"] = m.Announce
	}
	if len(m.AnnounceList) > 0 {
		mi["announce-list"] = m.AnnounceList
	}
	if m.CreationDate != "" {
		mi["creation date"] = m.CreationDate
	}
	if m.Comment != "" {
		mi["comment"] = m.Comment
	}
	if m.CreatedBy != "" {
		mi["created by"] = m.CreatedBy
	}
	if m.Encoding != "" {
		mi["encoding"] = m.Encoding
	}
	bencode.Marshal(w, mi)
	return
}
开发者ID:liugenping,项目名称:Taipei-Torrent,代码行数:29,代码来源:metainfo.go

示例5: startSeed

// startSeed attempts to start up a seeding process for a given torrent file.
func (self *Tracker) startSeed(file *File, metadata *Metadata) {
	self.seedStartLock.Lock()

	if file.SeedCommand != nil {
		self.seedStartLock.Unlock()
		return
	}

	tmp, err := ioutil.TempFile("", "distributor.")
	if err != nil {
		LogFatal("TempFile failed: %s", err)
	}
	LogDebug("Temporary file for %s: %s", file.Name, tmp.Name())

	err = bencode.Marshal(tmp, *metadata)
	if err != nil {
		self.seedStartLock.Unlock()
		LogError("Failed to bencode %s: %s", file.Name, err)
		return
	}

	err = tmp.Sync()
	if err != nil {
		self.seedStartLock.Unlock()
		LogError("Failed to fsync: %s", err)
		return
	}

	file.SeedCommand = exec.Command(
		self.ctorrent,
		"-s",
		file.FQFN,
		"-e",
		"4",
		"-p",
		"8999",
		tmp.Name())
	self.seedStartLock.Unlock()

	// TODO: Read from output pipes, because they could fill up?

	go func() {
		LogDebug("Seed starting: %s", file.Name)
		file.SeedCommand.Run()
		LogDebug("Seed exited: %s", file.Name)

		// Try to clean up temporary file.
		tmp.Close()
		os.Remove(tmp.Name())

		// Seeds exit after 4 hours. Then they get restarted if someone requests them.
		self.seedStartLock.Lock()
		file.SeedCommand = nil
		self.seedStartLock.Unlock()
	}()
}
开发者ID:andreimatei,项目名称:distributor,代码行数:57,代码来源:tracker.go

示例6: handleScrape

func (t *Tracker) handleScrape(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	infoHashes := r.URL.Query()["info_hash"]
	response := make(bmap)
	response["files"] = t.t.scrape(infoHashes)
	var b bytes.Buffer
	err := bencode.Marshal(&b, response)
	if err == nil {
		w.Write(b.Bytes())
	}
}
开发者ID:jackpal,项目名称:Taipei-Torrent,代码行数:11,代码来源:tracker.go

示例7: EncodeRequest

// EncodeRequest - Marshals message onto Bencode format
func (dht *DHTClient) EncodeRequest(req DHTMessage) string {
	if req.Command == "" {
		return ""
	}
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		return ""
	}
	return b.String()
}
开发者ID:subutai-io,项目名称:p2p,代码行数:12,代码来源:dht.go

示例8: ReportControlPeerLoad

// ReportControlPeerLoad - sends current amount of clients on this proxy
func (dht *DHTClient) ReportControlPeerLoad(amount int) {
	var req DHTMessage
	req.ID = dht.ID
	req.Command = DhtCmdLoad
	req.Arguments = fmt.Sprintf("%d", amount)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		return
	}
	dht.Send(b.String())
}
开发者ID:subutai-io,项目名称:p2p,代码行数:13,代码来源:dht.go

示例9: sendMsg

// sendMsg bencodes the data in 'query' and sends it to the remote node.
func sendMsg(conn *net.UDPConn, raddr net.UDPAddr, query interface{}) {
	totalSent.Add(1)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, query); err != nil {
		return
	}
	if n, err := conn.WriteToUDP(b.Bytes(), &raddr); err != nil {
		// debug.Println("DHT: node write failed:", err)
	} else {
		totalWrittenBytes.Add(int64(n))
	}
	return
}
开发者ID:postfix,项目名称:dht,代码行数:14,代码来源:krpc.go

示例10: sendMsg

// sendMsg bencodes the data in 'query' and sends it to the remote node.
func sendMsg(conn *net.UDPConn, raddr net.UDPAddr, query interface{}) {
	totalSent.Add(1)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, query); err != nil {
		return
	}
	if n, err := conn.WriteToUDP(b.Bytes(), &raddr); err != nil {
		log.V(3).Infof("DHT: node write failed to %+v, error=%s", raddr, err)
	} else {
		totalWrittenBytes.Add(int64(n))
	}
	return
}
开发者ID:kissthink,项目名称:dht,代码行数:14,代码来源:krpc.go

示例11: handleAnnounce

func (t *Tracker) handleAnnounce(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	response := make(bmap)
	var params announceParams
	var peerListenAddress *net.TCPAddr
	err := params.parse(r.URL)
	if err == nil {
		if params.trackerID != "" && params.trackerID != t.ID {
			err = fmt.Errorf("Incorrect tracker ID: %#v", params.trackerID)
		}
	}
	if err == nil {
		peerListenAddress, err = newTrackerPeerListenAddress(r.RemoteAddr, &params)
	}
	if err == nil {
		now := time.Now()
		t.m.Lock()
		err = t.t.handleAnnounce(now, peerListenAddress, &params, response)
		t.m.Unlock()
		if err == nil {
			response["interval"] = int64(30 * 60)
			response["tracker id"] = t.ID
		}
	}
	var b bytes.Buffer
	if err != nil {
		log.Printf("announce from %v failed: %#v", r.RemoteAddr, err.Error())
		errorResponse := make(bmap)
		errorResponse["failure reason"] = err.Error()
		err = bencode.Marshal(&b, errorResponse)
	} else {
		err = bencode.Marshal(&b, response)
	}
	if err == nil {
		w.Write(b.Bytes())
	}
}
开发者ID:jackpal,项目名称:Taipei-Torrent,代码行数:37,代码来源:tracker.go

示例12: UpdateInfoHash

// Updates the InfoHash field. Call this after manually changing the Info data.
func (m *MetaInfo) UpdateInfoHash(metaInfo *MetaInfo) (err error) {
	var b bytes.Buffer
	infoMap := m.Info.toMap()
	if len(infoMap) > 0 {
		err = bencode.Marshal(&b, infoMap)
		if err != nil {
			return
		}
	}
	hash := sha1.New()
	hash.Write(b.Bytes())

	m.InfoHash = string(hash.Sum(nil))
	return
}
开发者ID:liugenping,项目名称:Taipei-Torrent,代码行数:16,代码来源:metainfo.go

示例13: Stop

// Stop - sends a STOP message about current peer
func (dht *DHTClient) Stop() {
	dht.Shutdown = true
	var req DHTMessage
	req.ID = dht.ID
	req.Command = DhtCmdStop
	req.Arguments = "0"
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		return
	}
	msg := b.String()
	for _, conn := range dht.Connection {
		conn.Write([]byte(msg))
	}
}
开发者ID:subutai-io,项目名称:p2p,代码行数:17,代码来源:dht.go

示例14: sendMsg

// sendMsg bencodes the data in 'query' and sends it to the remote node.
func sendMsg(conn *net.UDPConn, raddr net.UDPAddr, query interface{}) error {
	totalSent.Add(1)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, query); err != nil {
		return err
	}
	if n, err := conn.WriteToUDP(b.Bytes(), &raddr); err != nil {
		if denet.ErrorIsPortUnreachable(err) {
			fmt.Println("DHT: port unreachable: ", err)
			return err
		}

		// all other errors are quashed
		//fmt.Println("DHT: node write failed:", err)
	} else {
		totalWrittenBytes.Add(int64(n))
	}
	return nil
}
开发者ID:hlandauf,项目名称:dht,代码行数:20,代码来源:krpc.go

示例15: trackerHandler

func trackerHandler(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("compact") != "1" {
		http.Error(w, "Only compact protocol supported.", 400)
		return
	}

	info_hash := dht.InfoHash(r.FormValue("info_hash"))
	if len(info_hash) != 20 {
		http.Error(w, "Bad info_hash.", 400)
		return
	}

	response := TrackerResponse{
		Interval:    300,
		MinInterval: 60,
	}

	peers, ok := peerCache.Get(info_hash)

	dhtNode.Find(info_hash)

	if !ok || len(peers) == 0 {
		response.Interval = 30
		response.MinInterval = 10

		time.Sleep(5 * time.Second)

		peers, ok = peerCache.Get(info_hash)
	}

	if ok && len(peers) > 0 {
		response.Incomplete = len(peers)
		response.Peers = strings.Join(peers, "")
	}

	w.Header().Set("Content-Type", "application/octet-stream")

	if err := bencode.Marshal(w, response); err != nil {
		http.Error(w, err.Error(), 500)
	}
}
开发者ID:die-net,项目名称:dhtproxy,代码行数:41,代码来源:tracker.go


注:本文中的github.com/jackpal/bencode-go.Marshal函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。