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


Golang torrent.NewClient函数代码示例

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


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

示例1: TestDownloadOnDemand

func TestDownloadOnDemand(t *testing.T) {
	layout, err := newGreetingLayout()
	require.NoError(t, err)
	defer layout.Destroy()
	seeder, err := torrent.NewClient(&torrent.Config{
		DataDir:         layout.Completed,
		DisableTrackers: true,
		NoDHT:           true,
		ListenAddr:      "localhost:0",
		Seed:            true,
		// Ensure that the metainfo is obtained over the wire, since we added
		// the torrent to the seeder by magnet.
		DisableMetainfoCache: true,
	})
	require.NoError(t, err)
	defer seeder.Close()
	testutil.ExportStatusWriter(seeder, "s")
	_, err = seeder.AddMagnet(fmt.Sprintf("magnet:?xt=urn:btih:%s", layout.Metainfo.Info.Hash.HexString()))
	require.NoError(t, err)
	leecher, err := torrent.NewClient(&torrent.Config{
		DisableTrackers: true,
		NoDHT:           true,
		ListenAddr:      "localhost:0",
		DisableTCP:      true,
		DefaultStorage:  storage.NewMMap(filepath.Join(layout.BaseDir, "download")),
		// This can be used to check if clients can connect to other clients
		// with the same ID.
		// PeerID: seeder.PeerID(),
	})
	require.NoError(t, err)
	testutil.ExportStatusWriter(leecher, "l")
	defer leecher.Close()
	leecherTorrent, _ := leecher.AddTorrent(layout.Metainfo)
	leecherTorrent.AddPeers([]torrent.Peer{
		torrent.Peer{
			IP:   missinggo.AddrIP(seeder.ListenAddr()),
			Port: missinggo.AddrPort(seeder.ListenAddr()),
		},
	})
	fs := New(leecher)
	defer fs.Destroy()
	root, _ := fs.Root()
	node, _ := root.(fusefs.NodeStringLookuper).Lookup(netContext.Background(), "greeting")
	var attr fuse.Attr
	node.Attr(netContext.Background(), &attr)
	size := attr.Size
	resp := &fuse.ReadResponse{
		Data: make([]byte, size),
	}
	node.(fusefs.HandleReader).Read(netContext.Background(), &fuse.ReadRequest{
		Size: int(size),
	}, resp)
	assert.EqualValues(t, testutil.GreetingFileContents, resp.Data)
}
开发者ID:CaptainIlu,项目名称:cloud-torrent,代码行数:54,代码来源:torrentfs_test.go

示例2: Configure

func (e *Engine) Configure(c Config) error {
	//recieve config
	if e.client != nil {
		e.client.Close()
	}
	tc := torrent.Config{
		DataDir:   c.DownloadDirectory,
		ConfigDir: filepath.Join(c.DownloadDirectory, ".config"),
		NoUpload:  !c.EnableUpload,
		Seed:      c.EnableSeeding,
	}
	client, err := torrent.NewClient(&tc)
	if err != nil {
		return err
	}
	e.mut.Lock()
	e.cacheDir = filepath.Join(tc.ConfigDir, "torrents")
	if files, err := ioutil.ReadDir(e.cacheDir); err == nil {
		for _, f := range files {
			if filepath.Ext(f.Name()) != ".torrent" {
				continue
			}
			tt, err := client.AddTorrentFromFile(filepath.Join(e.cacheDir, f.Name()))
			if err == nil {
				e.upsertTorrent(tt)
			}
		}
	}
	e.config = c
	e.client = client
	e.mut.Unlock()
	//reset
	e.GetTorrents()
	return nil
}
开发者ID:fieryrain,项目名称:cloud-torrent,代码行数:35,代码来源:engine.go

示例3: main

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&opts, tagflag.SkipBadTypes())
	clientConfig := opts.Config
	if opts.Mmap {
		clientConfig.TorrentDataOpener = func(info *metainfo.Info) torrent.Data {
			ret, err := mmap.TorrentData(info, "")
			if err != nil {
				log.Fatalf("error opening torrent data for %q: %s", info.Name, err)
			}
			return ret
		}
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if opts.Seed {
		select {}
	}
}
开发者ID:jaswinder-singh,项目名称:torrentsaga,代码行数:33,代码来源:main.go

示例4: main

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&flags)
	var clientConfig torrent.Config
	if flags.Mmap {
		clientConfig.DefaultStorage = storage.NewMMap("")
	}
	if flags.Addr != nil {
		clientConfig.ListenAddr = flags.Addr.String()
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	// Write status on the root path on the default HTTP muxer. This will be
	// bound to localhost somewhere if GOPPROF is set, thanks to the envpprof
	// import.
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if flags.Seed {
		select {}
	}
}
开发者ID:ymonk,项目名称:torrent,代码行数:33,代码来源:main.go

示例5: main

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&opts, tagflag.SkipBadTypes())
	clientConfig := opts.Config
	if opts.Mmap {
		clientConfig.DefaultStorage = storage.NewMMap("")
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if opts.Seed {
		select {}
	}
}
开发者ID:CaptainIlu,项目名称:cloud-torrent,代码行数:27,代码来源:main.go

示例6: NewClient

// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(torrentPath string, port int, seed bool) (client Client, err error) {
	var t torrent.Torrent
	var c *torrent.Client

	client.Port = port

	// Create client.
	c, err = torrent.NewClient(&torrent.Config{
		DataDir:  os.TempDir(),
		NoUpload: !seed,
		Seed:     seed,
	})

	if err != nil {
		return client, ClientError{Type: "creating torrent client", Origin: err}
	}

	client.Client = c

	// Add torrent.

	// Add as magnet url.
	if strings.HasPrefix(torrentPath, "magnet:") {
		if t, err = c.AddMagnet(torrentPath); err != nil {
			return client, ClientError{Type: "adding torrent", Origin: err}
		}
	} else {
		// Otherwise add as a torrent file.

		// If it's online, we try downloading the file.
		if isHTTP.MatchString(torrentPath) {
			if torrentPath, err = downloadFile(torrentPath); err != nil {
				return client, ClientError{Type: "downloading torrent file", Origin: err}
			}
		}

		// Check if the file exists.
		if _, err = os.Stat(torrentPath); err != nil {
			return client, ClientError{Type: "file not found", Origin: err}
		}

		if t, err = c.AddTorrentFromFile(torrentPath); err != nil {
			return client, ClientError{Type: "adding torrent to the client", Origin: err}
		}
	}

	client.Torrent = t

	go func() {
		<-t.GotInfo()
		t.DownloadAll()

		// Prioritize first 5% of the file.
		client.getLargestFile().PrioritizeRegion(0, int64(t.NumPieces()/100*5))
	}()

	go client.addBlocklist()

	return
}
开发者ID:thesyncim,项目名称:go-peerflix,代码行数:62,代码来源:client.go

示例7: New

func New(uri string) (*Downloader, string, error) {
	var err error

	var id string
	var client *torrent.Client
	var downloader = &Downloader{}

	id = utils.CalcMd5(uri)

	downloader.Id = id

	client, err = torrent.NewClient(&torrent.Config{
		DataDir:  filepath.Join(os.TempDir(), "gochromecast"),
		NoUpload: true,
		Seed:     true,
	})

	if err != nil {
		return downloader, id, errors.New(
			errors.DOWNLOADER_CANNOT_CREATE_TCLIENT_CODE,
			errors.DOWNLOADER_CANNOT_CREATE_TCLIENT_MESSAGE,
			err,
		)
	}
	downloader.Client = client
	return downloader, id, nil
}
开发者ID:bmartynov,项目名称:gochromecast,代码行数:27,代码来源:downloader.go

示例8: main

func main() {
	flag.Parse()
	cl, err := torrent.NewClient(nil)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	wg := sync.WaitGroup{}
	for _, arg := range flag.Args() {
		t, err := cl.AddMagnet(arg)
		if err != nil {
			log.Fatalf("error adding magnet to client: %s", err)
		}
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-t.GotInfo()
			mi := t.Metainfo()
			t.Drop()
			f, err := os.Create(mi.Info.Name + ".torrent")
			if err != nil {
				log.Fatalf("error creating torrent metainfo file: %s", err)
			}
			defer f.Close()
			err = bencode.NewEncoder(f).Encode(mi)
			if err != nil {
				log.Fatalf("error writing torrent metainfo file: %s", err)
			}
		}()
	}
	wg.Wait()
}
开发者ID:CaptainIlu,项目名称:cloud-torrent,代码行数:31,代码来源:main.go

示例9: NewClient

// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(cfg ClientConfig) (client Client, err error) {
	var t *torrent.Torrent
	var c *torrent.Client

	client.Config = cfg

	// Create client.
	c, err = torrent.NewClient(&torrent.Config{
		DataDir:    os.TempDir(),
		NoUpload:   !cfg.Seed,
		Seed:       cfg.Seed,
		DisableTCP: !cfg.TCP,
		ListenAddr: fmt.Sprintf(":%d", cfg.TorrentPort),
	})

	if err != nil {
		return client, ClientError{Type: "creating torrent client", Origin: err}
	}

	client.Client = c

	// Add torrent.

	// Add as magnet url.
	if strings.HasPrefix(cfg.TorrentPath, "magnet:") {
		if t, err = c.AddMagnet(cfg.TorrentPath); err != nil {
			return client, ClientError{Type: "adding torrent", Origin: err}
		}
	} else {
		// Otherwise add as a torrent file.

		// If it's online, we try downloading the file.
		if isHTTP.MatchString(cfg.TorrentPath) {
			if cfg.TorrentPath, err = downloadFile(cfg.TorrentPath); err != nil {
				return client, ClientError{Type: "downloading torrent file", Origin: err}
			}
		}

		if t, err = c.AddTorrentFromFile(cfg.TorrentPath); err != nil {
			return client, ClientError{Type: "adding torrent to the client", Origin: err}
		}
	}

	client.Torrent = t
	client.Torrent.SetMaxEstablishedConns(cfg.MaxConnections)

	go func() {
		<-t.GotInfo()
		t.DownloadAll()

		// Prioritize first 5% of the file.
		client.getLargestFile().PrioritizeRegion(0, int64(t.NumPieces()/100*5))
	}()

	go client.addBlocklist()

	return
}
开发者ID:Sioro-Neoku,项目名称:go-peerflix,代码行数:60,代码来源:client.go

示例10: Example

func Example() {
	c, _ := torrent.NewClient(nil)
	defer c.Close()
	t, _ := c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU")
	<-t.GotInfo()
	t.DownloadAll()
	c.WaitAll()
	log.Print("ermahgerd, torrent downloaded")
}
开发者ID:jpillora,项目名称:torrent,代码行数:9,代码来源:example_test.go

示例11: NewClient

// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(torrentPath string) (client Client, err error) {
	var t torrent.Torrent
	var c *torrent.Client

	// Create client.
	c, err = torrent.NewClient(&torrent.Config{
		DataDir:  os.TempDir(),
		NoUpload: !(*seed),
	})

	if err != nil {
		return client, ClientError{Type: "creating torrent client", Origin: err}
	}

	client.Client = c

	// Add torrent.

	// Add as magnet url.
	if strings.HasPrefix(torrentPath, "magnet:") {
		if t, err = c.AddMagnet(torrentPath); err != nil {
			return client, ClientError{Type: "adding torrent", Origin: err}
		}
	} else {
		// Otherwise add as a torrent file.

		// If it's online, we try downloading the file.
		if isHTTP.MatchString(torrentPath) {
			if torrentPath, err = downloadFile(torrentPath); err != nil {
				return client, ClientError{Type: "downloading torrent file", Origin: err}
			}
		}

		// Check if the file exists.
		if _, err = os.Stat(torrentPath); err != nil {
			return client, ClientError{Type: "file not found", Origin: err}
		}

		if t, err = c.AddTorrentFromFile(torrentPath); err != nil {
			return client, ClientError{Type: "adding torrent to the client", Origin: err}
		}
	}

	client.Torrent = t

	go func() {
		<-t.GotInfo()
		t.DownloadAll()
	}()

	return
}
开发者ID:testbots,项目名称:go-peerflix,代码行数:54,代码来源:client.go

示例12: SetConfig

func (n *Native) SetConfig(obj interface{}) error {
	//recieve config
	c, ok := obj.(*config)
	if !ok {
		return fmt.Errorf("Invalid config")
	}

	client, err := torrent.NewClient(&c.Config)
	if err != nil {
		return err
	}
	n.client = client
	return nil
}
开发者ID:prithi,项目名称:cloud-torrent,代码行数:14,代码来源:native.go

示例13: NewClient

func NewClient(downloadFolder string) (*Client, error) {
	client, err := torrent.NewClient(&torrent.Config{
		DataDir:    downloadFolder,
		NoUpload:   false,
		Seed:       true,
		DisableTCP: false,
	})
	if err != nil {
		return nil, ClientError{Type: "creating torrent client", Origin: err}
	}

	return &Client{
		Client:         client,
		downloadFolder: downloadFolder,
	}, nil
}
开发者ID:bbirec,项目名称:PeerPlayer,代码行数:16,代码来源:client.go

示例14: NewBuiltin

func NewBuiltin(dataDir string) (builtin *Builtin, err error) {
	cfg := &torrent.Config{
		DataDir: dataDir,
		Seed:    true,
		NoDHT:   true,
	}

	client, err := torrent.NewClient(cfg)
	if err != nil {
		return
	}

	builtin = &Builtin{
		Client: client,
	}
	return
}
开发者ID:ywk253100,项目名称:registry_p2p,代码行数:17,代码来源:builtin.go

示例15: Configure

func (e *Engine) Configure(c Config) error {
	//recieve config
	if e.client != nil {
		e.client.Close()
		time.Sleep(1 * time.Second)
	}
	if c.IncomingPort <= 0 {
		return fmt.Errorf("Invalid incoming port (%d)", c.IncomingPort)
	}
	tc := torrent.Config{
		DataDir:           c.DownloadDirectory,
		ListenAddr:        "0.0.0.0:" + strconv.Itoa(c.IncomingPort),
		NoUpload:          !c.EnableUpload,
		Seed:              c.EnableSeeding,
		DisableEncryption: c.DisableEncryption,
	}
	client, err := torrent.NewClient(&tc)
	if err != nil {
		return err
	}
	e.mut.Lock()
	e.cacheDir = filepath.Join(c.DownloadDirectory, ".config", "magnets")
	os.MkdirAll(e.cacheDir, 0777)
	if files, err := ioutil.ReadDir(e.cacheDir); err == nil {
		for _, f := range files {
			if filepath.Ext(f.Name()) != ".magnet" {
				continue
			}

			b, err := ioutil.ReadFile(filepath.Join(e.cacheDir, f.Name()))
			if err == nil {
				tt, err := client.AddMagnet(string(b[:]))
				if err == nil {
					e.upsertTorrent(tt)
				}
			}
		}
	}
	e.config = c
	e.client = client
	e.mut.Unlock()
	//reset
	e.GetTorrents()
	return nil
}
开发者ID:Zarloc,项目名称:cloud-torrent,代码行数:45,代码来源:engine.go


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