Beispiel #1
0
    /// <summary>
    /// играть за белых
    /// </summary>
    public void PlayAsWhite()
    {
        SenderState scriptToAccess = stateOBJ.GetComponent <SenderState>();

        scriptToAccess.SetColor(0);
        Debug.Log("Color setted is 0");
        Application.LoadLevel("Scene");
    }
 public TwoChoicesExtendedObliviousTransferChannelBase(ITwoChoicesObliviousTransferChannel baseOT, int securityParameter, CryptoContext cryptoContext)
 {
     RandomNumberGenerator = new ThreadsafeRandomNumberGenerator(cryptoContext.RandomNumberGenerator);
     RandomOracleProvider  = new HashRandomOracleProvider(cryptoContext.HashAlgorithmProvider);
     SecurityParameter     = securityParameter;
     _baseOT        = baseOT;
     _senderState   = new SenderState();
     _receiverState = new ReceiverState();
 }
Beispiel #3
0
        /// <summary>
        /// 发送消息并在本地处理
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="priority">0:最高优先级,-1:最低优先级</param>
        /// <param name="proc">调用方法</param>
        /// <returns></returns>
        public object ProcessData(object data, int priority, MsgQueue.MessageProc proc)
        {
            State = SenderState.Busy;
            DataSent d = PushData(MsgQueue.msgtype_Request, data, priority, proc);

            requestThread = Thread.CurrentThread;
            d.evt.WaitOne();
            requestThread = null;
            State         = SenderState.Idle;
            return(d.retData);
        }
Beispiel #4
0
        /// <summary>
        /// 发送消息并请求响应
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="priority">0:最高优先级,-1:最低优先级</param>
        /// <returns></returns>
        public object RequestData(object data, int priority)
        {
            State = SenderState.Waiting;
            DataSent d = PushData(MsgQueue.msgtype_Request, data, priority, null);

            requestThread = Thread.CurrentThread;
            d.evt.WaitOne();
            requestThread = null;
            State         = SenderState.Idle;
            return(d.retData);
        }
Beispiel #5
0
    /// <summary>
    /// при создании кадра происходит до Start . создаем и заполняем доску
    /// </summary>
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);

        AIOBJ    = GameObject.Find("AI");
        stateOBJ = GameObject.Find("StateMessanger");
        SenderState scriptToAccessOBJ = stateOBJ.GetComponent <SenderState>();

        State2 = scriptToAccessOBJ.color;
        State  = scriptToAccessOBJ.color;
        filing_table();
    }
Beispiel #6
0
        //init
        public DispatchProcessor(SenderState <TKey> hubState, IDispatchQueue <TKey> dispatchQueue,
                                 ILogger logger, SenderSettings senderSettings, IDispatchChannelRegistry <TKey> channelRegistry,
                                 IEnumerable <IDispatchProcessingCommand <TKey> > processingCommands)
            : base(logger)
        {
            _hubState           = hubState;
            _dispatchQueue      = dispatchQueue;
            _channelRegistry    = channelRegistry;
            _processingCommands = processingCommands
                                  .OrderBy(x => x.Order)
                                  .ToArray();

            MaxParallelItems = senderSettings.MaxParallelDispatchesProcessed;
        }
Beispiel #7
0
        //init
        public EventProcessor(SenderState <TKey> hubState, IMonitor <TKey> eventSink
                              , ILogger logger, SenderSettings senderSettings
                              , IEventQueue <TKey> eventQueue, IDispatchQueue <TKey> dispatchQueue
                              , IEventHandlerRegistry <TKey> handlerRegistry, IEventSettingsQueries <TKey> eventSettingsQueries)
            : base(logger)
        {
            _hubState             = hubState;
            _monitor              = eventSink;
            _eventQueue           = eventQueue;
            _dispatchQueue        = dispatchQueue;
            _handlerRegistry      = handlerRegistry;
            _eventSettingsQueries = eventSettingsQueries;

            MaxParallelItems = senderSettings.MaxParallelEventsProcessed;
        }
Beispiel #8
0
    /// <summary>
    /// ставятся настройки и обновляются все фигуры
    /// </summary>
    void Start()
    {
        SetGameSettings();
        UpdateFigures();



        stateOBJ = GameObject.Find("StateMessanger");


        SenderState scriptToAccessOBJ = stateOBJ.GetComponent <SenderState>();


        if (scriptToAccessOBJ.color == 1)   // если изначальный цвет 1 то мы передаем ход АИ
        {
            To_AI();
        }
    }
Beispiel #9
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                SenderState sender = (SenderState)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = sender.Socket.EndSend(ar);
                Console.WriteLine("" + localParty.Type + " sent {0} bytes to " + sender.To, bytesSent);

                // Signal that all bytes have been sent.
                sendDone[sender.To].Set();
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.ToString());
            }
        }
        /// <summary>
        /// Performs k many 1-out-of-2 OTs on k bits for the sender, where k is the security parameter, using the base OT implementation.
        ///
        /// These are subsequently expanded into m many 1oo2 OTs on arbitrarily long messages
        /// by the SendAsync method, where m is only bounded by the amount of secure randomness the random
        /// oracle implementation can produce.
        /// </summary>
        public async Task ExecuteSenderBaseOTAsync()
        {
            _senderState = new SenderState();
            _senderState.RandomChoices = RandomNumberGenerator.GetBits(SecurityParameter);

            // retrieve seeds for OT extension via _securityParameter many base OTs
            int requiredBytes = BitArray.RequiredBytes(SecurityParameter);

            byte[][] seeds = await _baseOT.ReceiveAsync(_senderState.RandomChoices, SecurityParameter, requiredBytes);

            Debug.Assert(seeds.Length == SecurityParameter);

            // initializing a random oracle based on each seed
            _senderState.SeededRandomOracles = new IEnumerable <byte> [SecurityParameter];
            for (int k = 0; k < SecurityParameter; ++k)
            {
                Debug.Assert(seeds[k].Length == requiredBytes);
                _senderState.SeededRandomOracles[k] = RandomOracleProvider.Create().Invoke(seeds[k]);
            }
        }
Beispiel #11
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                SenderState sender = (SenderState)ar.AsyncState;

                // Complete the connection.
                sender.Socket.EndConnect(ar);

                // Console.WriteLine("" + localParty.Type + " connected to {0}",
                //     sender.Socket.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                connectDone[sender.To].Set();
            }
            catch (Exception e)
            {
                // ConnectCallback(ar);
                // Console.WriteLine(e.ToString());
            }
        }
Beispiel #12
0
        // Main loop of the sender
        public void Run()
        {
            // Transfer state
            SenderState state         = SenderState.WaitingForFileRequest;
            string      requestedFile = "";
            IPEndPoint  receiver      = null;

            // This is a handly little function to reset the transfer state
            Action ResetTransferState = new Action(() =>
            {
                state         = SenderState.WaitingForFileRequest;
                requestedFile = "";
                receiver      = null;
                _blocks.Clear();
            });

            while (Running)
            {
                // Check for some new messages
                _checkForNetworkMessages();
                NetworkMessage nm = (_packetQueue.Count > 0) ? _packetQueue.Dequeue() : null;

                // Check to see if we have a BYE
                bool isBye = (nm == null) ? false : nm.Packet.IsBye;
                if (isBye)
                {
                    // Set back to the original state
                    ResetTransferState();
                    Console.WriteLine("Received a BYE message, waiting for next client.");
                }

                // Do an action depending on the current state
                switch (state)
                {
                case SenderState.WaitingForFileRequest:
                    // Check to see that we got a file request

                    // If there was a packet, and it's a request file, send and ACK and switch the state
                    bool isRequestFile = (nm == null) ? false : nm.Packet.IsRequestFile;
                    if (isRequestFile)
                    {
                        // Prepare the ACK
                        RequestFilePacket REQF = new RequestFilePacket(nm.Packet);
                        AckPacket         ACK  = new AckPacket();
                        requestedFile = REQF.Filename;

                        // Print info
                        Console.WriteLine("{0} has requested file file \"{1}\".", nm.Sender, requestedFile);

                        // Check that we have the file
                        if (_transferableFiles.Contains(requestedFile))
                        {
                            // Mark that we have the file, save the sender as our current receiver
                            receiver    = nm.Sender;
                            ACK.Message = requestedFile;
                            state       = SenderState.PreparingFileForTransfer;

                            Console.WriteLine("  We have it.");
                        }
                        else
                        {
                            ResetTransferState();
                        }

                        // Send the message
                        byte[] buffer = ACK.GetBytes();
                        _client.Send(buffer, buffer.Length, nm.Sender);
                    }
                    break;

                case SenderState.PreparingFileForTransfer:
                    // Using the requested file, prepare it in memory
                    byte[] checksum;
                    UInt32 fileSize;
                    if (_prepareFile(requestedFile, out checksum, out fileSize))
                    {
                        // It's good, send an info Packet
                        InfoPacket INFO = new InfoPacket();
                        INFO.Checksum     = checksum;
                        INFO.FileSize     = fileSize;
                        INFO.MaxBlockSize = MaxBlockSize;
                        INFO.BlockCount   = Convert.ToUInt32(_blocks.Count);

                        // Send it
                        byte[] buffer = INFO.GetBytes();
                        _client.Send(buffer, buffer.Length, receiver);

                        // Move the state
                        Console.WriteLine("Sending INFO, waiting for ACK...");
                        state = SenderState.WaitingForInfoACK;
                    }
                    else
                    {
                        ResetTransferState();       // File not good, reset the state
                    }
                    break;

                case SenderState.WaitingForInfoACK:
                    // If it is an ACK and the payload is the filename, we're good
                    bool isAck = (nm == null) ? false : (nm.Packet.IsAck);
                    if (isAck)
                    {
                        AckPacket ACK = new AckPacket(nm.Packet);
                        if (ACK.Message == "INFO")
                        {
                            Console.WriteLine("Starting Transfer...");
                            state = SenderState.Transfering;
                        }
                    }
                    break;

                case SenderState.Transfering:
                    // If there is a block request, send it
                    bool isRequestBlock = (nm == null) ? false : nm.Packet.IsRequestBlock;
                    if (isRequestBlock)
                    {
                        // Pull out data
                        RequestBlockPacket REQB = new RequestBlockPacket(nm.Packet);
                        Console.WriteLine("Got request for Block #{0}", REQB.Number);

                        // Create the response packet
                        Block      block = _blocks[REQB.Number];
                        SendPacket SEND  = new SendPacket();
                        SEND.Block = block;

                        // Send it
                        byte[] buffer = SEND.GetBytes();
                        _client.Send(buffer, buffer.Length, nm.Sender);
                        Console.WriteLine("Sent Block #{0} [{1} bytes]", block.Number, block.Data.Length);
                    }
                    break;
                }

                Thread.Sleep(1);
            }

            // If there was a receiver set, that means we need to notify it to shutdown
            if (receiver != null)
            {
                Packet BYE    = new Packet(Packet.Bye);
                byte[] buffer = BYE.GetBytes();
                _client.Send(buffer, buffer.Length, receiver);
            }

            state = SenderState.NotRunning;
        }
        void StoreDataAndNotify(HttpContext context, HttpRequest req, string commitSourceID)
        {
            string csDataDir = Path.Combine (Path.Combine (Config.Instance.RootPath, "data"), commitSourceID);

            if (!Directory.Exists (csDataDir)) {
                try {
                    Directory.CreateDirectory (csDataDir);
                } catch (Exception ex) {
                    Log (ex, "Failed to create data directory '{0}'", csDataDir);
                    InvalidRequest (context.Response, 500);
                    return;
                }
            }

            DateTime now = DateTime.Now;
            string fileName = Path.Combine (csDataDir, now.Ticks.ToString () + ".json");
            try {
                using (var writer = new FileStream (fileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    byte[] data = new byte[INPUT_BUFFER_LENGTH];
                    Stream input = req.InputStream;
                    int rlen;
                    while ((rlen = input.Read (data, 0, INPUT_BUFFER_LENGTH)) > 0)
                        writer.Write (data, 0, rlen);
                }
            } catch (Exception ex) {
                Log (ex, "Failed to write posted data to file '{4}'. Exception '{1}' was caught: '{2}'", fileName);
                InvalidRequest (context.Response, 500);
                return;
            }

            var state = new SenderState () {
                CsDataDir = csDataDir,
                CommitSourceID = commitSourceID
            };
            ThreadPool.QueueUserWorkItem (Sender, state);
        }
Beispiel #14
0
 void ks_threadSessionStateChanged(SenderState state)
 {
     switch(state)
     {
         case SenderState.Started:
             toolStrip2.Invoke(new VoidMethod(SetStartedState));
             break;
         case SenderState.Stopped:
             toolStrip2.Invoke(new VoidMethod(SetStoppedState));
             break;
         default:break;
     }
 }
Beispiel #15
0
 private void Send(SenderState sender, byte[] data)
 {
     // Begin sending the data to the remote device.
     sender.Socket.BeginSend(data, 0, data.Length, 0,
                             new AsyncCallback(SendCallback), sender);
 }
Beispiel #16
0
        // one thread is constantly scan the buffer for all parties
        private void FlushBuffer()
        {
            Dictionary <PartyType, Stopwatch> stopwatch = new Dictionary <PartyType, Stopwatch>();

            foreach (var party in msgBuffer.Keys)
            {
                stopwatch.Add(party, new Stopwatch());
                stopwatch[party].Start();
            }
            while (!receiver.hasReceivedEOP)
            {
                foreach (var party in msgBuffer.Keys)
                {
                    bool reachBufferThreshold = false, reachTimeThreshold = false;
                    switch (party)
                    {
                    //case PartyType.Client:
                    //    reachBufferThreshold = msgBuffer[party].Count >= Config.Runtime_Network_BufferMessageThresholdClient;
                    //    break;
                    case PartyType.EVH:
                        reachBufferThreshold = msgBuffer[party].Count >= Config.Runtime_Network_BufferMessageThresholdEVH;
                        break;

                    case PartyType.KH:
                        reachBufferThreshold = msgBuffer[party].Count >= Config.Runtime_Network_BufferMessageThresholdKH;
                        break;

                    case PartyType.Helper:
                        reachBufferThreshold = msgBuffer[party].Count >= Config.Runtime_Network_BufferMessageThresholdHelper;
                        break;

                    default:
                        break;
                    }
                    stopwatch[party].Stop();
                    reachTimeThreshold = stopwatch[party].ElapsedMilliseconds >= Config.Runtime_Network_TimeThreshold;
                    stopwatch[party].Start();
                    if (reachBufferThreshold || reachTimeThreshold)
                    {
                        List <byte[]> msgs = msgBuffer[party].Retrieve();

                        //// if buffer already contains a null referance, which means there will be no more messages
                        //if (msgBuffer[party].IsComplete)
                        //{
                        //    // decrement notEmptyBufferCount
                        //    --notEmptyBufferCount;
                        //}

                        // once messages are delivered, resart the stopwatch
                        stopwatch[party].Restart();

                        // if message buffer is not empty, send the message
                        if (msgs.Count != 0)
                        {
                            try
                            {
                                // Create a TCP/IP socket.
                                Socket socket = new Socket(AddressFamily.InterNetwork,
                                                           SocketType.Stream, ProtocolType.Tcp);

                                SenderState sender = new SenderState(socket, party);

                                // Connect to the remote endpoint.
                                socket.BeginConnect(partyIPMap[party],
                                                    new AsyncCallback(ConnectCallback), sender);
                                connectDone[party].WaitOne();

                                // send data to remote party
                                byte[] data = Message.Pack(localParty.Type, msgs);
                                Send(sender, data);
                                sendDone[party].WaitOne();

                                // Release the socket.
                                socket.Shutdown(SocketShutdown.Both);
                                socket.Close();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.ToString());
                                // break the while(true) loop
                                break;
                            }
                        }
                    }
                }
            }
        }