Example #1
0
        private void HandshakeMessageReceived(IMessageReceivedContext context)
        {
            var data      = context.Reader.ReadBytes(context.MessageLength - 1);
            var handshake = new ExtensionProtocolHandshake();

            handshake.Deserialize(data);
            context.SetValue(ExtensionProtocolMessageIds, handshake.MessageIds);
        }
        void IModule.OnPeerConnected(IPeerContext context)
        {
            // Check for extension protocol support
            bool supportsExtensionProtocol = (context.Peer.ReservedBytes[5] & 0x10) != 0;

            if (!supportsExtensionProtocol)
            {
                return;
            }

            // Register to receive extension protocol messages
            context.RegisterMessageHandler(ExtensionProtocolMessageId);

            // Send handshake message
            var handshake = new ExtensionProtocolHandshake
            {
                MessageIds = _supportedMessages,
                Client     = "TorrentCore 0.1", // todo
            };

            var handshakeDict = handshake.Serialize();

            var prepareHandshakeContext =
                new PrepareExtensionProtocolHandshakeContext(
                    handshakeDict,
                    context,
                    msg => SendExtensionMessage(context, msg));

            foreach (var handler in _registeredHandlers)
            {
                handler.PrepareExtensionProtocolHandshake(prepareHandshakeContext);
            }

            SendMessage(context, writer =>
            {
                writer.Write((byte)0);
                writer.Flush();
                handshakeDict.EncodeTo(writer.BaseStream);
            });
        }