Ignore:
Timestamp:
Nov 17, 2009, 1:05:15 PM (12 years ago)
Author:
arnold
Message:

Buggy P2P version

Location:
trunk/CrypPlugins/PeerToPeerBase
Files:
45 edited

Legend:

Unmodified
Added
Removed
  • trunk/CrypPlugins/PeerToPeerBase/IP2PControl.cs

    r836 r862  
    3434    public enum PubSubMessageType
    3535    {
     36        /// <summary>
     37        /// To register the subscriber with the publisher
     38        /// </summary>
    3639        Register = 0,
    37         Alive = 1,
    38         Ping = 2,
    39         Pong = 3
     40        /// <summary>
     41        /// adequate response to a subscriber-sided
     42        /// registering message
     43        /// </summary>
     44        RegisteringAccepted = 1,
     45        /// <summary>
     46        /// when peer wants to leave the publish/subscriber union
     47        /// </summary>
     48        Unregister = 2,
     49        /// <summary>
     50        /// To signalize the publisher that subscriber is still online/alive
     51        /// </summary>
     52        Alive = 3,
     53        /// <summary>
     54        /// active liveliness-request, the other side
     55        /// must respond with a pong message
     56        /// </summary>
     57        Ping = 4,
     58        /// <summary>
     59        /// adequate response to a
     60        /// received ping message
     61        /// </summary>
     62        Pong = 5,
     63        /// <summary>
     64        /// subscriber sends this msg when solution was found
     65        /// </summary>
     66        Solution = 6,
     67        /// <summary>
     68        /// to immediately stop the subscribers work
     69        /// </summary>
     70        Stop = 7,
     71        /// <summary>
     72        /// because Enum is non-nullable, I used this workaround
     73        /// </summary>
     74        NULL = 666
    4075    }
    4176    #endregion
     
    4883        bool DHTremove(string sKey);
    4984
    50         byte[] GetPeerID(out string sPeerName);
    51 
    52         string ConvertPeerId(byte[] bytePeerId);
     85        string GetPeerID(out string sPeerName);
     86        //byte[] GetPeerID(out string sPeerName);
    5387
    5488        void SendToPeer(string sData, byte[] sDestinationPeerAddress);
     89        void SendToPeer(string sData, string sDestinationPeerAddress);
     90        void SendToPeer(PubSubMessageType msgType, string sDestinationAddress);
     91
     92        PubSubMessageType GetMsgType(string byteData);
    5593
    5694        event P2PBase.P2PMessageReceived OnPeerReceivedMsg;
  • trunk/CrypPlugins/PeerToPeerBase/P2PPeer.cs

    r836 r862  
    2525using Cryptool.PluginBase.IO;
    2626
     27
     28/*
     29 * TODO:
     30 * - Build a stable P2PPeer Version (only valid when initialized!)
     31 * - Integrate struct PeerId into functions and other classes,
     32 *   particularly P2PPublisherBase
     33 */
    2734namespace Cryptool.Plugins.PeerToPeer
    2835{
     
    4653        #endregion
    4754
     55        #region Standard functionality
     56
    4857        public P2PPeer()
    4958        {
     
    5160            // to forward event from overlay/dht MessageReceived-Event from P2PBase
    5261            this.p2pBase.OnP2PMessageReceived += new P2PBase.P2PMessageReceived(p2pBase_OnP2PMessageReceived);
    53             this.settings = new P2PPeerSettings(p2pBase);
     62            this.settings = new P2PPeerSettings(this);
    5463            this.settings.TaskPaneAttributeChanged += new TaskPaneAttributeChangedHandler(settings_TaskPaneAttributeChanged);
    5564            this.settings.OnPluginStatusChanged += new StatusChangedEventHandler(settings_OnPluginStatusChanged);
     
    5968        private void settings_OnPluginStatusChanged(IPlugin sender, StatusEventArgs args)
    6069        {
    61             if (OnPluginStatusChanged != null) OnPluginStatusChanged(this, args);
     70            if (OnPluginStatusChanged != null)
     71                OnPluginStatusChanged(this, args);
    6272        }
    6373
    6474        // to forward event from overlay/dht MessageReceived-Event from P2PBase
    65         private void p2pBase_OnP2PMessageReceived(byte[] byteSourceAddr, string sData)
     75        private void p2pBase_OnP2PMessageReceived(string sSourceAddr, string sData)
    6676        {
    6777            if (OnPeerMessageReceived != null)
    68                 OnPeerMessageReceived(byteSourceAddr, sData);
     78                OnPeerMessageReceived(sSourceAddr, sData);
    6979        }
    7080
     
    7383            //throw new NotImplementedException();
    7484        }
    75 
    76         #region IPlugin Members
    77 
    78         public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
    79 
    80         public event PluginProgressChangedEventHandler OnPluginProgressChanged;
    8185
    8286        public ISettings Settings
     
    105109            else
    106110            {
    107                 if (!settings.PeerStarted)
    108                 {
    109                     // starts peer in the settings class and enables/disables Controlbuttons
    110                     this.settings.PeerStarted = true;
    111                     GuiLogMessage("Successfully joined the P2P System", NotificationLevel.Info);
    112                 }
     111                StartPeer();
    113112            }
    114113        }
     
    118117            // TODO: For future use copy functionality to Execute instead of PreExecute
    119118            //       so we don't need the workaround anymore!!!
    120             //if (!settings.PeerStarted)
    121             //{
    122             //    // starts peer in the settings class and enables/disables Controlbuttons
    123             //    this.settings.PeerStarted = true;
    124             //}
    125         }
    126 
    127         public void process(IP2PControl sender)
    128         {
    129             GuiLogMessage("P2P Peer method 'process' is executed, because status of P2PSlave has changed!", NotificationLevel.Debug);
     119            // StartPeer();
    130120        }
    131121
     
    148138        public void Dispose()
    149139        {
    150             //settings are already set to null in this Step...
    151             //unsolved design problem in CT2...
    152             //this.settings.PeerStopped = true;
    153             if (this.p2pBase != null)
    154             {
    155                 this.p2pBase.SynchStop();
    156                 this.p2pBase = null;
    157             }
    158         }
    159 
    160         #endregion
     140            StopPeer();
     141        }
     142
     143        #endregion
     144
     145        #region IPlugin Members
     146
     147        public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
     148
     149        public event PluginProgressChangedEventHandler OnPluginProgressChanged;
     150
     151        #endregion
    161152
    162153        #region INotifyPropertyChanged Members
     
    195186                return this.p2pSlave;
    196187            }
    197             set
    198             {
    199                 if (this.p2pSlave != null)
    200                 {
    201                     this.p2pSlave.OnStatusChanged -= p2pSlave_OnStatusChanged;
    202                 }
    203 
    204                 this.p2pSlave.OnStatusChanged += new IControlStatusChangedEventHandler(p2pSlave_OnStatusChanged);
    205                 //Only when using asynchronous p2p-Start-method, add event handler for OnPeerJoinedCompletely
    206                 //this.p2pSlave.OnPeerJoinedCompletely += new PeerJoinedP2P(OnPeerJoinedCompletely);
    207 
    208                 if (this.p2pSlave != value)
    209                 {
    210                     this.p2pSlave = (P2PPeerMaster)value;
    211                     OnPropertyChanged("P2PControlSlave");
    212                 }
    213             }
    214         }
    215 
    216         void p2pSlave_OnStatusChanged(IControl sender, bool readyForExecution)
    217         {
    218             if (readyForExecution)
    219                 this.process((IP2PControl)sender);
    220         }
    221 
     188        }
     189
     190        #endregion
     191
     192        #region Start and Stop Peer
     193
     194        /// <summary>
     195        /// Status flag for starting and stopping peer only once.
     196        /// </summary>
     197        private bool peerStarted = false;
     198
     199        public void StartPeer()
     200        {
     201            if (!this.peerStarted)
     202            {
     203                if (this.p2pBase == null)
     204                {
     205                    this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Error);
     206                    GuiLogMessage("Starting Peer failed, because Base-Object is null.",NotificationLevel.Error);
     207                    return;
     208                }
     209
     210                this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Connecting);
     211
     212                this.p2pBase.Initialize(this.settings.P2PPeerName, this.settings.P2PWorldName,
     213                    (P2PLinkManagerType)this.settings.P2PLinkMngrType, (P2PBootstrapperType)this.settings.P2PBSType,
     214                    (P2POverlayType)this.settings.P2POverlType, (P2PDHTType)this.settings.P2PDhtType);
     215                this.peerStarted = this.p2pBase.SynchStart();
     216
     217                if (this.peerStarted)
     218                {
     219                    this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Online);
     220                    GuiLogMessage("Successfully joined the P2P System", NotificationLevel.Info);
     221                }
     222                else
     223                {
     224                    this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Error);
     225                    GuiLogMessage("Joining to P2P System failed!", NotificationLevel.Error);
     226                }
     227            }
     228            else
     229            {
     230                GuiLogMessage("Peer is already started!", NotificationLevel.Warning);
     231            }
     232        }
     233
     234        public void StopPeer()
     235        {
     236            if (this.peerStarted && this.p2pBase != null)
     237            {
     238                this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Connecting);
     239
     240                this.peerStarted = !this.p2pBase.SynchStop();
     241
     242                if (this.peerStarted)
     243                {
     244                    this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.Online);
     245                    GuiLogMessage("Peer stopped: " + !this.peerStarted, NotificationLevel.Warning);
     246                }
     247                else
     248                {
     249                    this.settings.PeerStatusChanged(P2PPeerSettings.PeerStatus.NotConnected);
     250                    GuiLogMessage("Peer stopped: " + !this.peerStarted, NotificationLevel.Info);
     251                }
     252            }
     253            else
     254            {
     255                GuiLogMessage("Peer is already stopped!", NotificationLevel.Warning);
     256            }
     257        }
     258
     259        public void LogInternalState()
     260        {
     261            if(this.p2pBase != null)
     262                this.p2pBase.LogInternalState();
     263        }
    222264        #endregion
    223265    }
     
    226268    {
    227269        private P2PPeer p2pPeer;
    228         private byte[] bytePeerID;
    229270        private string sPeerID;
    230271        private string sPeerName;
    231272
     273        /* Required because comparing a byte-array is inefficient */
     274        // TODO: Previously unused!
     275        public struct PeerId
     276        {
     277            string stringId;
     278            byte[] byteId;
     279        }
     280
    232281        public P2PPeerMaster(P2PPeer p2pPeer)
    233282        {
    234283            this.p2pPeer = p2pPeer;
     284            //if (this.p2pPeer.p2pBase == null && this.p2pPeer.p2pBase.Initialized)
     285            //{
     286            //    throw (new Exception("P2PBase isn't completely initialized!"));
     287            //}
    235288            // to forward event from overlay/dht MessageReceived-Event from P2PBase
    236289            this.p2pPeer.OnPeerMessageReceived += new P2PBase.P2PMessageReceived(p2pPeer_OnPeerMessageReceived);
     
    242295        // to forward event from overlay/dht MessageReceived-Event from P2PBase
    243296        public event P2PBase.P2PMessageReceived OnPeerReceivedMsg;
    244         private void p2pPeer_OnPeerMessageReceived(byte[] byteSourceAddr, string sData)
     297        private void p2pPeer_OnPeerMessageReceived(string sSourceAddr, string sData)
    245298        {
    246299            if (OnPeerReceivedMsg != null)
    247                 OnPeerReceivedMsg(byteSourceAddr, sData);
     300                OnPeerReceivedMsg(sSourceAddr, sData);
    248301        }
    249302
     
    276329        public bool DHTremove(string sKey)
    277330        {
    278             // derzeit liegt wohl in peerq@play ein Fehler in der Methode...
    279             // erkennt den Übergabeparameter nicht an und wirft dann "ArgumentNotNullException"...
    280             // Problem an M.Helling und S.Holzapfel von p@p weitergegeben...
    281331            return this.p2pPeer.p2pBase.SynchRemove(sKey);
    282             //return false;
    283332        }
    284333
     
    288337        /// <param name="sPeerName">returns the Peer Name</param>
    289338        /// <returns>returns the Peer ID</returns>
    290         public byte[] GetPeerID(out string sPeerName)
    291         {
    292             if (this.bytePeerID == null)
    293             {
    294                 this.bytePeerID = this.p2pPeer.p2pBase.GetPeerID(out this.sPeerName);
    295                 this.sPeerID = ConvertPeerId(bytePeerID);
     339        public string GetPeerID(out string sPeerName)
     340        {
     341            if (this.sPeerID == null)
     342            {
     343                this.sPeerID = this.p2pPeer.p2pBase.GetPeerID(out this.sPeerName);
    296344            }
    297345            sPeerName = this.sPeerName;
    298             return this.bytePeerID;
    299         }
    300 
    301         public string ConvertPeerId(byte[] bytePeerId)
    302         {
    303             string sRet = String.Empty;
    304             for (int i = 0; i < bytePeerId.Length; i++)
    305             {
    306                 sRet += bytePeerId[i].ToString() + ":";
    307             }
    308             return sRet.Substring(0, sRet.Length - 1);
    309         }
    310 
     346            return this.sPeerID;
     347        }
     348
     349        public void SendToPeer(string sData, string sDestinationPeerAddress)
     350        {
     351            this.p2pPeer.p2pBase.SendToPeer(sData, sDestinationPeerAddress);
     352        }
    311353        public void SendToPeer(string sData, byte[] byteDestinationPeerAddress)
    312354        {
    313355            this.p2pPeer.p2pBase.SendToPeer(sData, byteDestinationPeerAddress);
    314356        }
     357        public void SendToPeer(PubSubMessageType msgType, string sDestinationAddress)
     358        {
     359            this.p2pPeer.p2pBase.SendToPeer(msgType, sDestinationAddress);
     360        }
     361
     362        /// <summary>
     363        /// Converts a string to the PubSubMessageType if possible. Otherwise return null.
     364        /// </summary>
     365        /// <param name="sData">Data</param>
     366        /// <returns>PubSubMessageType if possible. Otherwise null.</returns>
     367        public PubSubMessageType GetMsgType(string sData)
     368        {
     369            // Convert one byte data to PublishSubscribeMessageType-Enum
     370            int iMsg;
     371            if (sData.Trim().Length == 1 && Int32.TryParse(sData.Trim(), out iMsg))
     372            {
     373                return (PubSubMessageType)iMsg;
     374            }
     375            else
     376            {
     377                // because Enum is non-nullable, I used this workaround
     378                return PubSubMessageType.NULL;
     379            }
     380        }
    315381
    316382        #endregion
    317383    }
    318 
    319     //public class P2PPeerMaster : IP2PControl
    320     //{
    321     //    private P2PBase p2pBase;
    322 
    323     //    public P2PPeerMaster(P2PBase p2pBase)
    324     //    {
    325     //        this.p2pBase = p2pBase;
    326     //        this.OnPeerReceivedMsg += new P2PBase.P2PMessageReceived(P2PPeerMaster_OnPeerReceivedMsg);
    327     //        this.OnStatusChanged += new IControlStatusChangedEventHandler(P2PPeerMaster_OnStatusChanged);
    328     //    }
    329 
    330     //    #region Events and Event-Handling
    331 
    332     //    public event P2PBase.P2PMessageReceived OnPeerReceivedMsg;
    333     //    private void P2PPeerMaster_OnPeerReceivedMsg(byte[] byteSourceAddr, string sData)
    334     //    {
    335     //        if (OnPeerReceivedMsg != null)
    336     //            OnPeerReceivedMsg(byteSourceAddr, sData);
    337     //    }
    338 
    339     //    public event IControlStatusChangedEventHandler OnStatusChanged;
    340     //    private void P2PPeerMaster_OnStatusChanged(IControl sender, bool readyForExecution)
    341     //    {
    342     //        if (OnStatusChanged != null)
    343     //            OnStatusChanged(sender, readyForExecution);
    344     //    }
    345 
    346     //    #endregion
    347 
    348     //    #region IP2PControl Members
    349 
    350     //    public bool DHTstore(string sKey, string sValue)
    351     //    {
    352     //        return this.p2pBase.SynchStore(sKey, sValue);
    353     //    }
    354 
    355     //    public byte[] DHTload(string sKey)
    356     //    {
    357     //        return this.p2pBase.SynchRetrieve(sKey);
    358     //    }
    359 
    360     //    public bool DHTremove(string sKey)
    361     //    {
    362     //        // derzeit liegt wohl in peerq@play ein Fehler in der Methode...
    363     //        // erkennt den Übergabeparameter nicht an und wirft dann "ArgumentNotNullException"...
    364     //        // Problem an M.Helling und S.Holzapfel von p@p weitergegeben...
    365     //        return this.p2pBase.SynchRemove(sKey);
    366     //        //return false;
    367     //    }
    368 
    369     //    public byte[] GetPeerName()
    370     //    {
    371     //        return this.p2pBase.GetPeerName();
    372     //    }
    373 
    374     //    public void SendToPeer(string sData, byte[] byteDestinationPeerAddress)
    375     //    {
    376     //        this.p2pBase.SendToPeer(sData, byteDestinationPeerAddress);
    377     //    }
    378 
    379     //    #endregion
    380     //}
    381384}
  • trunk/CrypPlugins/PeerToPeerBase/P2PPeerSettings.cs

    r836 r862  
    1616
    1717        private bool hasChanges = false;
    18         private P2PBase p2pBase;
     18        private P2PPeer p2pPeer;
    1919
    2020        #region ISettings Members
     
    3636        #region taskPane
    3737
    38         public P2PPeerSettings (P2PBase p2pBase)
     38        public P2PPeerSettings (P2PPeer p2pPeer)
    3939            {
    4040            if(TaskPaneAttributeChanged != null)
    4141                TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnStop", Visibility.Hidden)));
    42             this.p2pBase = p2pBase;
     42            this.p2pPeer = p2pPeer;
    4343            ChangePluginIcon(PeerStatus.NotConnected);
    4444            }
     
    4848        #region Start- and Stop-Buttons incl. functionality
    4949
    50         [TaskPane("Start", "Initializes and starts Peer", null, 3, false, DisplayLevel.Beginner, ControlType.Button)]
     50        public bool StartingPeer
     51        {
     52            set
     53            {
     54                if (value)
     55                {
     56                    BtnStart();
     57                }
     58            }
     59        }
     60
     61        [TaskPane("Start", "Initializes and starts Peer", null, 2, false, DisplayLevel.Beginner, ControlType.Button)]
    5162        public void BtnStart()
    5263        {
    53             PeerStarted = !this.peerStarted;
    54         }
    55 
    56         private bool peerStarted = false;
    57         /// <summary>
    58         /// If peer isn't started by clicking the Button, it will be started by setting to true
    59         /// </summary>
    60         public bool PeerStarted
    61         {
    62             get { return this.peerStarted; }
    63             set
    64             {
    65                 if (!this.peerStarted)
    66                 {
    67                     if (P2PPeerName != null && P2PWorldName != null)
    68                     {
    69                         ChangePluginIcon(PeerStatus.Connecting);
    70                         this.p2pBase.Initialize(P2PPeerName, P2PWorldName, (P2PLinkManagerType)P2PLinkMngrType,
    71                             (P2PBootstrapperType)P2PBSType, (P2POverlayType)P2POverlType, (P2PDHTType)P2PDhtType);
    72                         this.p2pBase.SynchStart();
    73                         TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnStart", Visibility.Collapsed)));
    74                         TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnStop", Visibility.Visible)));
    75                         ChangePluginIcon(PeerStatus.Online);
    76                     }
    77                     else
    78                     {
    79                         ChangePluginIcon(PeerStatus.Error);
    80                         // can not initialize Peer, because P2PUserName and/or P2PWorldName are missing
    81                         throw (new Exception("You must set P2PPeerName and/or P2PWorldName, otherwise starting the peer isn't possible"));
    82                     }
    83                 }
    84                 if (value != this.peerStarted)
    85                 {
    86                     this.peerStarted = value;
    87                     //use the private Var instead of the PeerStopped-Property, because you will run into a recursive loop!!!
    88                     this.peerStopped = !value;
    89                     OnPropertyChanged("PeerStarted");
    90                     HasChanges = true;
    91                 }
    92             }
    93         }
    94 
    95         [TaskPane("Stop", "Stops the Peer", null, 4, false, DisplayLevel.Beginner, ControlType.Button)]
     64            if (P2PPeerName != null && P2PWorldName != null)
     65            {
     66                this.p2pPeer.StartPeer();
     67            }
     68            else
     69            {
     70                PeerStatusChanged(PeerStatus.Error);
     71                // can not initialize Peer, because P2PUserName and/or P2PWorldName are missing
     72                throw (new Exception("You must set P2PPeerName and/or P2PWorldName, otherwise starting the peer isn't possible"));
     73            }
     74        }
     75
     76        [TaskPane("Stop", "Stops the Peer", null, 3, false, DisplayLevel.Beginner, ControlType.Button)]
    9677        public void BtnStop()
    9778        {
    98             PeerStopped = !this.peerStopped;
    99         }
    100 
    101         private bool peerStopped = true;
    102         /// <summary>
    103         /// if peer is already started, it will be stopped by setting to true
    104         /// </summary>
    105         public bool PeerStopped
    106         {
    107             get { return this.peerStopped; }
    108             set
    109             {
    110                 if (this.peerStarted)
    111                 {
    112                     ChangePluginIcon(PeerStatus.Connecting);
    113                     this.p2pBase.SynchStop();
    114                     TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnStart", Visibility.Visible)));
    115                     TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnStop", Visibility.Collapsed)));
    116                     ChangePluginIcon(PeerStatus.NotConnected);
    117                 }
    118                 if (value != this.peerStopped)
    119                 {
    120                     //don't use the PeerStarted-Property, because you will run into a recursive loop!!!
    121                     this.peerStarted = !value;
    122                     this.peerStopped = value;
    123                     OnPropertyChanged("PeerStopped");
    124                     HasChanges = true;
    125                 }
    126             }
     79            this.p2pPeer.StopPeer();
     80         
     81            OnPropertyChanged("PeerStopped");
     82            HasChanges = true;
     83        }
     84
     85        [TaskPane("Log internal state of peer", "Log internal state of peer", null, 4, false, DisplayLevel.Beginner, ControlType.Button)]
     86        public void BtnLogInternalState()
     87        {
     88            this.p2pPeer.LogInternalState();
    12789        }
    12890
     
    163125        }
    164126
    165         [TaskPane("Log internal state of peer", "Log internal state of peer", null, 2, false, DisplayLevel.Beginner, ControlType.Button)]
    166         public void btnTest()
    167         {
    168             this.p2pBase.LogInternalState();
    169         }
    170 
    171127        private P2PLinkManagerType p2pLinkManagerType = P2PLinkManagerType.Snal;
    172128        [TaskPane("LinkManager-Type", "Select the LinkManager-Type", "P2P Settings", 2, false, DisplayLevel.Beginner, ControlType.ComboBox, new string[] { "Snal" })]
     
    248204
    249205        // Index depends on icon-position in P2PPeer-Class properties
    250         private enum PeerStatus
     206        public enum PeerStatus
    251207        {
    252208            Connecting = 1,
     
    256212        }
    257213
     214        /// <summary>
     215        /// Changes icon of P2PPeer and visibility of the control buttons in settings
     216        /// </summary>
     217        /// <param name="peerStat"></param>
     218        public void PeerStatusChanged(PeerStatus peerStat)
     219        {
     220            ChangePluginIcon(peerStat);
     221            // Only set visibility in final states!
     222            switch (peerStat)
     223            {
     224                case PeerStatus.Online:
     225                    TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(
     226                        new TaskPaneAttribteContainer("BtnStart", Visibility.Collapsed)));
     227                    TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(
     228                        new TaskPaneAttribteContainer("BtnStop", Visibility.Visible)));
     229                    break;
     230                case PeerStatus.NotConnected:
     231                    TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(
     232                        new TaskPaneAttribteContainer("BtnStart", Visibility.Visible)));
     233                    TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(
     234                        new TaskPaneAttribteContainer("BtnStop", Visibility.Hidden)));
     235                    break;
     236                case PeerStatus.Error:
     237                case PeerStatus.Connecting:
     238                default:
     239                    break;
     240            }
     241        }
     242
    258243        public event StatusChangedEventHandler OnPluginStatusChanged;
    259244        private void ChangePluginIcon(PeerStatus peerStatus)
    260245        {
    261             if (OnPluginStatusChanged != null) OnPluginStatusChanged(null,
    262                 new StatusEventArgs(StatusChangedMode.ImageUpdate, (int)peerStatus));
     246            if (OnPluginStatusChanged != null)
     247                OnPluginStatusChanged(null, new StatusEventArgs(StatusChangedMode.ImageUpdate, (int)peerStatus));
    263248        }
    264249    }
  • trunk/CrypPlugins/PeerToPeerBase/PeerToPeerBase.cs

    r836 r862  
    3535using PeersAtPlay;
    3636
    37 /*
    38  * Synchronous functions successfully tested (store, retrieve)
    39  * !!! remove-Function is faulty - open field !!!
     37/* - Synchronous functions successfully tested (store, retrieve)
     38 * - !!! remove-Function is faulty - open field !!!
     39 * - The DHT has an integrated versioning system. When a peer wants
     40 *   to store data in an entry, which already holds data, the version
     41 *   number will be compared with the peers' version number. If the
     42 *   peer hasn't read/write the entry the last time, the storing instruction
     43 *   will be rejected. You must first read the actual data and than you can
     44 *   store your data in this entry...
     45 *
     46 * INFO:
     47 * - Have considered the DHT-own versioning system in the SynchStore method.
     48 *   If this versioning system will be abolished, the SynchStore method must
     49 *   be change!
    4050 *
    4151 * TODO:
     
    6979        public event SystemLeft OnSystemLeft;
    7080
    71         public delegate void P2PMessageReceived(byte[] byteSourceAddr, string sData);
     81        public delegate void P2PMessageReceived(string sSourceAddr, string sData);
    7282        public event P2PMessageReceived OnP2PMessageReceived;
    7383
     
    92102
    93103        #region Variables
     104
     105        private bool initialized = false;
     106        public bool Initialized
     107        {
     108            get { return this.initialized; }
     109            set { this.initialized = value; }
     110        }
    94111
    95112        private IDHT dht;
     
    196213        }
    197214
    198         /*TESTING AREA - COMPLETELY STOP THE WHOLE P2P SYSTEM*/
    199215        /// <summary>
    200216        /// Disjoins the peer from the system. The P2P system survive while one peer is still in the network.
     
    206222            {
    207223                this.dht.BeginStop(null);
    208                 //wait till systemLeft Event is invoked
    209224                this.overlay.BeginStop(null);
    210225                this.linkmanager.BeginStop(null);
    211226                this.bootstrapper.Dispose();
     227                //wait till systemLeft Event is invoked
    212228                this.systemLeft.WaitOne();
    213229            }
     
    249265        /// </summary>
    250266        /// <param name="sPeerName">out: additional peer information UserName on LinkManager</param>
    251         /// <returns>PeerID as an byte array (suitable for correct addressing on the overlay)</returns>
    252         public byte[] GetPeerID(out string sPeerName)
     267        /// <returns>PeerID as a String</returns>
     268        public string GetPeerID(out string sPeerName)
    253269        {
    254270            sPeerName = this.linkmanager.UserName;
    255             return this.overlay.LocalAddress.ToByteArray();
     271            return this.overlay.LocalAddress.ToString();
     272            // return this.overlay.LocalAddress.ToByteArray();
    256273        }
    257274
     
    271288        }
    272289
     290        public void SendToPeer(string sData, string sDestinationPeerId)
     291        {
     292            // necessary because the overlay.GetAddress(string)-method of PAP is very buggy.
     293            // It doesn't cast the string- to a Byte-Address, but returns the own address...
     294            string[] sSplitted = sDestinationPeerId.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
     295            byte[] byteDestinationAddress = new byte[sSplitted.Length];
     296            for (int i = 0; i < byteDestinationAddress.Length; i++)
     297            {
     298                byteDestinationAddress[i] = System.Convert.ToByte(sSplitted[i]);
     299            }
     300            SendToPeer(sData, byteDestinationAddress);
     301        }
     302
     303        public void SendToPeer(PubSubMessageType msgType, string sDestinationAddress)
     304        {
     305            SendToPeer(((int)msgType).ToString(), sDestinationAddress);
     306        }
     307
    273308        #region Event Handling (System Joined, Left and Message Received)
    274309
     
    278313                OnSystemJoined();
    279314            this.systemJoined.Set();
     315            Initialized = true;
    280316        }
    281317
     
    287323            this.dht = null;
    288324            this.systemLeft.Set();
     325            Initialized = false;
    289326        }
    290327
     
    292329        {
    293330            if (OnP2PMessageReceived != null)
    294                 OnP2PMessageReceived(e.Message.Source.ToByteArray(), e.Message.Data.PopUTF8String());
     331                OnP2PMessageReceived(e.Message.Source.ToString(), e.Message.Data.PopUTF8String());
    295332        }
    296333
     
    298335        {
    299336            if (OnP2PMessageReceived != null)
    300                 OnP2PMessageReceived(e.Source.ToByteArray(), e.Data.PopUTF8String());
     337                OnP2PMessageReceived(e.Source.ToString(), e.Data.PopUTF8String());
    301338        }
    302339
    303340        #endregion
    304341
    305         /*
    306          * Attention: The asynchronous methods are not tested at the moment
    307          */
     342        /* Attention: The asynchronous methods are not tested at the moment */
    308343        #region Asynchronous Methods incl. Callbacks
    309344
     
    372407        #region Synchronous Methods incl. Callbacks
    373408
     409        #region SynchStore incl.Callback and SecondTrialCallback
     410
     411        /* The DHT has an integrated VERSIONING SYSTEM. When a peer wants
     412         * to store data in an entry, which already holds data, the version
     413         * number will be compared with the peers' version number. If the
     414         * peer hasn't read/write the entry the last time, the storing instruction
     415         * will be rejected. You must first read the actual data and than you can
     416         * store your data in this entry... */
    374417        /// <summary>
    375418        /// Stores a value in the DHT at the given key
     
    384427            Guid g = this.dht.Store(OnSynchStoreCompleted, sKey, byteData);
    385428
    386             ResponseWait rw = new ResponseWait() { WaitHandle = are };
     429            ResponseWait rw = new ResponseWait() { WaitHandle = are, key=sKey , value = byteData };
    387430
    388431            waitDict.Add(g, rw);
    389432            //blocking till response
    390433            are.WaitOne();
    391             return true;
     434            return rw.success;
    392435        }
    393436
     
    402445            return SynchStore(sKey, UTF8Encoding.UTF8.GetBytes(sData));
    403446        }
     447        /// <summary>
     448        /// Callback for a the synchronized store method
     449        /// </summary>
     450        /// <param name="rr"></param>
     451        private void OnSynchStoreCompleted(StoreResult sr)
     452        {
     453            ResponseWait rw;
     454            if (this.waitDict.TryGetValue(sr.Guid, out rw))
     455            {
     456                // if Status == Error, than the version of the value is out of date.
     457                // There is a versioning system in the DHT. So you must retrieve the
     458                // key and than store the new value --> that's it, but much traffic.
     459                // to be fixed in a few weeks from M.Helling
     460                if (sr.Status == OperationStatus.Failure)
     461                {
     462                    byte[] byteTemp = this.SynchRetrieve(rw.key);
     463
     464                    // Only try a second time. When it's still not possible, abort storing
     465                    AutoResetEvent are = new AutoResetEvent(false);
     466                    Guid g = this.dht.Store(OnSecondTrialStoring, rw.key, rw.value);
     467                    ResponseWait rw2 = new ResponseWait() { WaitHandle = are, key = rw.key, value = rw.value };
     468
     469                    waitDict.Add(g, rw2);
     470                    // blocking till response
     471                    are.WaitOne();
     472                    rw.success = rw2.success;
     473                    rw.Message = rw2.Message;
     474                }
     475                else
     476                {
     477                    rw.Message = UTF8Encoding.UTF8.GetBytes(sr.Status.ToString());
     478                    if (sr.Status == OperationStatus.KeyNotFound)
     479                        rw.success = false;
     480                    else
     481                        rw.success = true;
     482                }
     483            }
     484            //unblock WaitHandle in the synchronous method
     485            rw.WaitHandle.Set();
     486            // don't know if this accelerates the system...
     487            this.waitDict.Remove(sr.Guid);
     488        }
     489
     490        private void OnSecondTrialStoring(StoreResult sr)
     491        {
     492            ResponseWait rw;
     493            if (this.waitDict.TryGetValue(sr.Guid, out rw))
     494            {
     495                if (sr.Status == OperationStatus.Failure)
     496                {
     497                    //Abort storing, because it's already the second trial
     498                    rw.Message = UTF8Encoding.UTF8.GetBytes("Storing also not possible on second trial.");
     499                    rw.success = false;
     500                }
     501                else
     502                {
     503                    //works the second trial, so it was the versioning system
     504                    rw.success = true;
     505                }
     506            }
     507            //unblock WaitHandle in the synchronous method
     508            rw.WaitHandle.Set();
     509            // don't know if this accelerates the system...
     510            this.waitDict.Remove(sr.Guid);
     511        }
     512
     513        #endregion
    404514
    405515        /// <summary>
     
    425535
    426536        /// <summary>
    427         /// Removes a key/value pair out of the DHT
    428         /// </summary>
    429         /// <param name="sKey">Key of the DHT Entry</param>
    430         /// <returns>True, when removing is completed!</returns>
    431         public bool SynchRemove(string sKey)
    432         {
    433             AutoResetEvent are = new AutoResetEvent(false);
    434             // this method returns always a GUID to distinguish between asynchronous actions
    435 
    436             // ROAD WORKS: This function throws an error (ArgumentNotNullException).
    437             //             I think that's an error in the p@p-environment --> forwarded to the p@p-Team
    438             Guid g = this.dht.Remove(OnSynchRemoveCompleted, sKey);
    439 
    440             ResponseWait rw = new ResponseWait() { WaitHandle = are };
    441 
    442             waitDict.Add(g, rw);
    443             // blocking till response
    444             are.WaitOne();
    445             return true;
    446         }
    447 
    448         /// <summary>
    449         /// Callback for a the synchronized store method
    450         /// </summary>
    451         /// <param name="rr"></param>
    452         private void OnSynchStoreCompleted(StoreResult sr)
    453         {
    454             ResponseWait rw;
    455             if (this.waitDict.TryGetValue(sr.Guid, out rw))
    456             {
    457                 // if Status == Error, than the version of the value is out of date.
    458                 // There is a versioning system in the DHT. So you must retrieve the
    459                 // key and than store the new value --> that's it, but much traffic.
    460                 // to be fixed in a few weeks from M.Helling
    461                 rw.Message = UTF8Encoding.UTF8.GetBytes(sr.Status.ToString());
    462 
    463                 //unblock WaitHandle in the synchronous method
    464                 rw.WaitHandle.Set();
    465                 // don't know if this accelerates the system...
    466                 this.waitDict.Remove(sr.Guid);
    467             }
    468         }
    469 
    470         /// <summary>
    471537        /// Callback for a the synchronized retrieval method
    472538        /// </summary>
     
    478544            if (this.waitDict.TryGetValue(rr.Guid, out rw))
    479545            {
    480                 rw.Message = rr.Data;
    481 
    482                 //unblock WaitHandle in the synchronous method
    483                 rw.WaitHandle.Set();
    484                 // don't know if this accelerates the system...
    485                 this.waitDict.Remove(rr.Guid);
    486             }
    487         }
    488 
    489         /// <summary>
    490         /// Callback for a the synchronized remove method
    491         /// </summary>
    492         /// <param name="rr"></param>
    493         private void OnSynchRemoveCompleted(RemoveResult rr)
    494         {
    495             ResponseWait rw;
    496             if (this.waitDict.TryGetValue(rr.Guid, out rw))
    497             {
    498                 rw.Message = UTF8Encoding.UTF8.GetBytes(rr.Status.ToString());
     546                // successful as long as no error occured
     547                rw.success = true;
     548                if (rr.Status == OperationStatus.Failure)
     549                {
     550                    rw.Message = null;
     551                    rw.success = false;
     552                }
     553                else if (rr.Status == OperationStatus.KeyNotFound)
     554                    rw.Message = null;
     555                else
     556                    rw.Message = rr.Data;
    499557
    500558                //unblock WaitHandle in the synchronous method
     
    504562            }
    505563        }
     564        /// <summary>
     565        /// Removes a key/value pair out of the DHT
     566        /// </summary>
     567        /// <param name="sKey">Key of the DHT Entry</param>
     568        /// <returns>True, when removing is completed!</returns>
     569        public bool SynchRemove(string sKey)
     570        {
     571            AutoResetEvent are = new AutoResetEvent(false);
     572            // this method returns always a GUID to distinguish between asynchronous actions
     573
     574            // ROAD WORKS: This function throws an error (ArgumentNotNullException).
     575            //             I think that's an error in the p@p-environment --> forwarded to the p@p-Team
     576            Guid g = this.dht.Remove(OnSynchRemoveCompleted, sKey);
     577
     578            ResponseWait rw = new ResponseWait() { WaitHandle = are };
     579
     580            waitDict.Add(g, rw);
     581            // blocking till response
     582            are.WaitOne();
     583            return rw.success;
     584        }
     585
     586        /// <summary>
     587        /// Callback for a the synchronized remove method
     588        /// </summary>
     589        /// <param name="rr"></param>
     590        private void OnSynchRemoveCompleted(RemoveResult rr)
     591        {
     592            ResponseWait rw;
     593            if (this.waitDict.TryGetValue(rr.Guid, out rw))
     594            {
     595                rw.Message = UTF8Encoding.UTF8.GetBytes(rr.Status.ToString());
     596
     597                if (rr.Status == OperationStatus.Failure || rr.Status == OperationStatus.KeyNotFound)
     598                    rw.success = false;
     599                else
     600                    rw.success = true;
     601
     602                //unblock WaitHandle in the synchronous method
     603                rw.WaitHandle.Set();
     604                // don't know if this accelerates the system...
     605                this.waitDict.Remove(rr.Guid);
     606            }
     607        }
    506608
    507609        #endregion
  • trunk/CrypPlugins/PeerToPeerBase/ResponseWait.cs

    r783 r862  
    1111        public AutoResetEvent WaitHandle = null;
    1212        public byte[] Message = null;
     13        public string key = null;
     14        public byte[] value = null;
     15
     16        public bool success = false;
    1317    }
    1418
Note: See TracChangeset for help on using the changeset viewer.