private void ClientThread()
        {
            Random random;

            lock (seeder)
            {
                random = new Random(seeder.Next());
            }

            Connection conn = new Connection();
            BlockingCollection <string> q = new BlockingCollection <string>();

            CountdownEvent allMessagesReceived = new CountdownEvent(messagesPerClient);

            conn.Received += (object sender, ReceivedEventArgs args) =>
            {
                if (args.OperationSucceeded)
                {
                    byte[] rdata = args.Data;
                    string r     = Encoding.ASCII.GetString(rdata);
                    string s     = q.Take();

                    if (r == s)
                    {
                        allMessagesReceived.Signal();
                    }
                    else
                    {
                        Assert.Fail();
                    }
                }
            };

            conn.Open(server.Address);

            for (int j = 0; j < messagesPerClient; j++)
            {
                string s    = RandomString(messageByteCount, random);
                byte[] data = Encoding.ASCII.GetBytes(s);
                q.Add(s);
                conn.Write(data.Length);
                conn.Write(data);
            }
            q.CompleteAdding();

            allMessagesReceived.Wait();
            conn.Close();
            allClientsDone.Signal();
        }
Example #2
0
        /// <summary>
        /// Worker method for sending commands
        /// </summary>
        private async void CommandWorker()
        {
            while (!_commandCancellationToken.IsCancellationRequested)
            {
                CurrentCommand = null;

                if (_queueSize == 0)
                {
                    _queueEmptyEvent.Set();
                }

                try
                {
                    if (_commandQueue.TryTake(out CurrentCommand, 10, _commandCancellationToken.Token))
                    {
                        _queueSize--;

                        Logger?.WriteLine("Writing Command: '" + CurrentCommand.CommandText.Replace('\r', '\'') + "'", OBDLogLevel.Verbose);

                        if (Connection.IsAsync)
                        {
                            await Connection.WriteAsync(Encoding.ASCII.GetBytes(CurrentCommand.CommandText));
                        }
                        else
                        {
                            Connection.Write(Encoding.ASCII.GetBytes(CurrentCommand.CommandText));
                        }

                        //wait for command to finish
                        _commandFinishedEvent.WaitOne();
                    }
                }
                catch (OperationCanceledException) { /*ignore, because it is thrown when the cancellation token is canceled*/ }
            }
        }
Example #3
0
        /// <summary>
        /// Requests the settings.
        /// </summary>
        public override void RequestSettings()
        {
            var message = new Message(Command.RequestSettings);

            message.Payload = new byte[2];
            Connection.Write(message);
        }
Example #4
0
        protected void LoginResult(byte type, List <byte> data)
        {
            UInt32 result = BitConverter.ToUInt32(data.ToArray(), 3);

            if (result != 0)
            {
                Logger.Write("Failed to log into character {0}", _character);
                throw new Exception();
            }

            BuildWritePacket(0x0b, System.Text.Encoding.ASCII.GetBytes(LodId));
            byte[] comma = { 0x2C };
            BuildWritePacket(0x0a, System.Text.Encoding.ASCII.GetBytes(_character),
                             Zero, System.Text.Encoding.ASCII.GetBytes(_realm),
                             comma, System.Text.Encoding.ASCII.GetBytes(_character), Zero);

            if (!_loggedIn)
            {
                byte[] packetc = Connection.BuildPacket(0x12);

                Connection.Write(packetc);
                _loggedIn = true;
            }
            OnUpdateStatus(Client.Status.StatusNotInGame);
        }
Example #5
0
        protected void EnterChat(byte type, List <byte> data)
        {
            Connection.Write(Connection.BuildPacket(0x46, Nulls));
            Connection.Write(Connection.BuildPacket(0x15, System.Text.Encoding.ASCII.GetBytes(Platform), System.Text.Encoding.ASCII.GetBytes(LodId), Nulls, BitConverter.GetBytes((uint)System.Environment.TickCount)));

            OnStartGameCreationThread();
        }
        private void CheckCommandsThread_DoWork(object sender)
        {
            foreach (var command in Commands2Check)
            {
                CommandInCheck = command;
                Connection.Write(command.Command);
                CommandInCheckResult = -1;

                int count = 0;
                while (CommandInCheckResult == -1)
                {
                    Thread.Sleep(1000);
                    count++;
                    if (count > 4)
                    {
                        break;
                    }
                }
            }
            Dispatcher.BeginInvoke(DispatcherPriority.Render,
                                   (Action)(() =>
            {
                DisplayResults();
            }));
        }
Example #7
0
        private void PrintFormat(object sender, DoWorkEventArgs e)
        {
            Dictionary <int, string> formatVars = GetFormatVariables();

            try {
                OpenConnection();
                ZebraPrinter printer = ZebraPrinterFactory.GetInstance(printerConnection);

                string statusMessage = GetPrinterStatus(printer.GetCurrentStatus());
                if (statusMessage != null)
                {
                    errorMessage = "Printer Error: " + statusMessage + ". Please check your printer and try again.";
                }
                else
                {
                    if (!lastFormatOpenedSource.Equals(FORMAT_SOURCE_PRINTER))
                    {
                        printerConnection.Write(Encoding.UTF8.GetBytes(lastFormatOpenedContents));
                    }

                    printer.PrintStoredFormat(lastFormatOpened, formatVars, "UTF-8");
                    statusMessage = GetPrinterStatus(printer.GetCurrentStatus());
                    if (statusMessage != null)
                    {
                        errorMessage = "Printer Error after Printing: " + statusMessage + ". Please check your printer.";
                    }
                }
            } catch (ConnectionException error) {
                errorMessage = "Connection Error: " + error.Message;
            } finally {
                CloseConnection();
            }
        }
 public Task LocalStart <T>(T instance)
     where T : class, new()
 {
     IsHost = true;
     Connection.Write(Id, new MemoryStream(InitBytes.ToByteArray(), false));
     return(Task.CompletedTask);
 }
Example #9
0
        public Listener(Uri url, DynamicObject opts, Connection callback)
        {
            listener = new HttpListener();
            listener.Prefixes.Add(url.AbsoluteUri);
            listener.Start();
            Port = url.Port;
            Dispatcher dispatcher       = Dispatcher.CurrentDispatcher;
            var        acceptConnection = new Action <HttpListenerContext>((HttpListenerContext context) =>
            {
                var request  = new Request(context.Request);
                var response = new Response(context.Response);

                if (opts != null)
                {
                    var keepAlive = ObjectHelpers.GetProperty(opts, "keepAlive");
                    if (!(keepAlive is Undefined) && (bool)keepAlive == true)
                    {
                        context.Response.KeepAlive = true;
                    }
                }
                callback.Write(request, response);
            });

            acceptLoop = Task.Run(async() =>
            {
                while (listener.IsListening)
                {
                    var context = await listener.GetContextAsync();
                    dispatcher.Invoke(acceptConnection, context);
                }
            });
        }
Example #10
0
        /// <summary>
        /// Requests the calibration.
        /// </summary>
        public override void RequestCalibration()
        {
            var message = new Message(Command.StartCalibration);

            message.Payload = new byte[2];
            Connection.Write(message);
        }
Example #11
0
        protected void HandleAdvertising(byte type, List <byte> data)
        {
            UInt32 ad_id = BitConverter.ToUInt32(data.ToArray(), 4);

            byte[] packet = Connection.BuildPacket((byte)0x21, System.Text.Encoding.ASCII.GetBytes(Platform), System.Text.Encoding.ASCII.GetBytes(LodId), BitConverter.GetBytes(ad_id), Zero, Zero);
            Connection.Write(packet);
        }
Example #12
0
        public override void SendCmd(Command cmd)
        {
            base.SendCmd(cmd);

            if ((cmd.CmdNum == 1 || cmd.CmdNum == 2) && cmd.CmdTypeID == BaseValues.CmdTypes.Binary)
            {
                if (cmd.CmdNum == 1)
                {
                    // send command data as string
                    // отправка данных команды как строки
                    string logText;
                    Connection.WriteLine(cmd.GetCmdDataStr(), out logText);
                    WriteToLog(logText);
                }
                else
                {
                    // send command data as array of bytes
                    // отправка данных команды как массива байт
                    string logText;
                    Connection.Write(cmd.CmdData, 0, cmd.CmdData.Length, CommUtils.ProtocolLogFormats.Hex,
                                     out logText);
                    WriteToLog(logText);
                }
            }
            else
            {
                WriteToLog(CommPhrases.IllegalCommand);
                lastCommSucc = false;
            }

            CalcCmdStats();
        }
Example #13
0
        /// <summary>
        /// Applies the settings.
        /// </summary>
        public override void ApplySettings()
        {
            var message = new Message(Command.ModifySettings);

            message.Payload = new byte[12];

            //Channel 1
            message.Payload[0] = 0;
            message.Payload[1] = 0;
            message.Payload[2] = (byte)Oscilloscope.Channels[0].InputCoupling;
            message.Payload[3] = (byte)Oscilloscope.Channels[0].VoltsPerDivision;
            message.Payload[4] = (byte)Oscilloscope.Channels[0].YPosition;

            //Channel 2
            message.Payload[5] = (byte)Oscilloscope.Channels[1].InputCoupling;
            message.Payload[6] = (byte)Oscilloscope.Channels[1].VoltsPerDivision;
            message.Payload[7] = (byte)Oscilloscope.Channels[1].YPosition;

            //Oscilloscope
            message.Payload[8]  = (byte)Oscilloscope.TimeBase;
            message.Payload[9]  = (byte)Oscilloscope.Trigger.Level;
            message.Payload[10] = EncodeTriggerSettings();
            message.Payload[11] = 0;

            Connection.Write(message);
        }
Example #14
0
 private static void Run(Connection connection)
 {
     while (connection.IsConnected())
     {
         connection.Write(Console.ReadLine());
     }
 }
Example #15
0
        /// <summary>
        /// Sends the telecontrol command.
        /// </summary>
        public override void SendCommand(TeleCommand cmd)
        {
            base.SendCommand(cmd);

            if (cmd.CmdCode == "SendStr" || cmd.CmdNum == 1)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                Connection.WriteLine(cmd.GetCmdDataString());

                stopwatch.Stop();
                Log.WriteLine(Locale.IsRussian ?
                              "Отправлено за {0} мс" :
                              "Sent in {0} ms", stopwatch.ElapsedMilliseconds);
            }
            else if (cmd.CmdCode == "SendBin" || cmd.CmdNum == 2)
            {
                byte[]    buffer    = cmd.CmdData ?? Array.Empty <byte>();
                Stopwatch stopwatch = Stopwatch.StartNew();
                Connection.Write(buffer, 0, buffer.Length);

                stopwatch.Stop();
                Log.WriteLine(Locale.IsRussian ?
                              "Отправлено за {0} мс" :
                              "Sent in {0} ms", stopwatch.ElapsedMilliseconds);
            }
            else
            {
                LastRequestOK = false;
                Log.WriteLine(CommPhrases.InvalidCommand);
            }

            FinishCommand();
        }
Example #16
0
        internal void Transmit(ushort channelNumber, Connection connection)
        {
            int maxBodyPayloadBytes = (int)(connection.FrameMax == 0 ? int.MaxValue : connection.FrameMax - EmptyFrameSize);
            var size = GetMaxSize(maxBodyPayloadBytes);

            // Will be returned by SocketFrameWriter.WriteLoop
            var memory = new Memory <byte>(ArrayPool <byte> .Shared.Rent(size), 0, size);
            var span   = memory.Span;

            var offset = Framing.Method.WriteTo(span, channelNumber, Method);

            if (Method.HasContent)
            {
                int remainingBodyBytes = Body.Length;
                offset += Framing.Header.WriteTo(span.Slice(offset), channelNumber, Header, remainingBodyBytes);
                var bodySpan = Body.Span;
                while (remainingBodyBytes > 0)
                {
                    int frameSize = remainingBodyBytes > maxBodyPayloadBytes ? maxBodyPayloadBytes : remainingBodyBytes;
                    offset             += Framing.BodySegment.WriteTo(span.Slice(offset), channelNumber, bodySpan.Slice(bodySpan.Length - remainingBodyBytes, frameSize));
                    remainingBodyBytes -= frameSize;
                }
            }

            if (offset != size)
            {
                throw new InvalidOperationException($"Serialized to wrong size, expect {size}, offset {offset}");
            }

            connection.Write(memory);
        }
        public void basicPrint(string zplbarcode, string lbl_one, string lbl_two, string lbl_three, string lbl_four, string lbl_five, string lbl_six)
        {
            List <DiscoveredPrinter> printerList = GetUSBPrinters();

            string zpl_string = "^XA"
                                + "^FX^FWr^CI28^CFA,40^FO100,50^A0B^FD" + lbl_one + "^FS^FO150,50^A0B^FD" + lbl_two + "^FS^FO200,50^A0B^FD" + lbl_three + "^FS^FO250,50^A0B^FD4MM^FS"
                                + "^FX fifth^FO595,320^A0B^FD" + lbl_four + "^FS"
                                + "^FXfifth formulation^FO510,30^A0B^FD" + lbl_five + "^FS"
                                + "^FXfourthsection with barcode."
                                + "^BY2,2.5,123^FO380,730^BCB,,N,N,N,A^FD" + zplbarcode + "^FS^CFA,40^FO320,730^A0B,0,0^FD" + zplbarcode + "^FS"
                                + "^FX fifth section"
                                + "^CF0,90^FO275,1145^A0B^FD" + lbl_six + "^FS"
                                + "^XZ";

            if (printerList.Count > 0)
            {
                // in this case, we arbitrarily are printing to the first found printer
                DiscoveredPrinter discoveredPrinter = printerList[0];
                Connection        connection        = discoveredPrinter.GetConnection();
                connection.Open();
                connection.Write(Encoding.UTF8.GetBytes(zpl_string));
            }
            else
            {
                Console.WriteLine("No Printers found to print to.");
            }
        }
Example #18
0
 private void FlushCore(TimeSpan timeout)
 {
     if (_pendingWriteSize > 0)
     {
         Connection.Write(_writeBuffer, 0, _pendingWriteSize, false, timeout);
         _pendingWriteSize = 0;
     }
 }
Example #19
0
 public void Save(string content)
 {
     _log.Write("Starting command");
     _connection.Open();
     _connection.Write(content);
     _connection.Close();
     _log.Write("finished command");
 }
Example #20
0
        protected void AccountLogin(byte type, List <byte> data)
        {
            UInt32      client_token = (uint)System.Environment.TickCount;
            List <byte> hash         = Bsha1.DoubleHash(client_token, _serverToken, _password);

            byte[] packet = Connection.BuildPacket((byte)0x3a, BitConverter.GetBytes(client_token), BitConverter.GetBytes(_serverToken), hash, System.Text.Encoding.ASCII.GetBytes(_account), Zero);
            Connection.Write(packet);
        }
Example #21
0
        /// <summary>
        /// Sends the wifi settings.
        /// </summary>
        public override void SendWifiSettings()
        {
            var message = new Message(Command.SendWifiSettings);

            message.Payload = new byte[68];
            EncodeWifiSettings(message);
            Connection.Write(message);
        }
 void FlushCore(TimeSpan timeout)
 {
     if (pendingWriteSize > 0)
     {
         Connection.Write(writeBuffer, 0, pendingWriteSize, false, timeout);
         pendingWriteSize = 0;
     }
 }
Example #23
0
        /// <summary>
        /// Worker method for sending commands
        /// </summary>
        private async void CommandWorker()
        {
            while (!_commandCancellationToken.IsCancellationRequested)
            {
                try
                {
                    CurrentCommand = null;

                    if (_queueSize == 0)
                    {
                        _queueEmptyEvent.Set();
                    }

                    try
                    {
                        if (_commandQueue.TryTake(out CurrentCommand, 10, _commandCancellationToken.Token))
                        {
                            Interlocked.Decrement(ref _queueSize);

                            Logger?.WriteLine("Writing Command: '" + CurrentCommand.CommandText.Replace('\r', '\'') + "'", OBDLogLevel.Verbose);

                            if (Connection.IsAsync)
                            {
                                await Connection.WriteAsync(Encoding.ASCII.GetBytes(CurrentCommand.CommandText));
                            }
                            else
                            {
                                // ReSharper disable once MethodHasAsyncOverload
                                Connection.Write(Encoding.ASCII.GetBytes(CurrentCommand.CommandText));
                            }

                            //wait for command to finish
                            if (CurrentCommand.WaitForResponse)
                            {
                                if (CurrentCommand.Timeout.HasValue)
                                {
                                    _commandFinishedEvent.WaitOne(CurrentCommand.Timeout.Value);
                                }
                                else
                                {
                                    _commandFinishedEvent.WaitOne();
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        /*ignore, because it is thrown when the cancellation token is canceled*/
                    }
                }
                catch (Exception ex)
                {
                    SocketError?.Invoke(this, new SocketErrorEventArgs(ex));
                    Connection.Dispose();
                }
            }
        }
Example #24
0
        protected void CharacterList(byte type, List <byte> data)
        {
            UInt16 count = BitConverter.ToUInt16(data.ToArray(), 9);

            if (count == 0)
            {
                OnUpdateStatus(Client.Status.StatusOnMcp);
            }
            else
            {
                bool foundCharacter       = false;
                bool selectFirstCharacter = false;

                //Console.WriteLine("{0}: [MCP] List of characters on this account", _owner.Account);
                int offset = 11;

                for (int i = 1; i <= count; i++)
                {
                    offset += 4;
                    String      dataString    = System.Text.Encoding.ASCII.GetString(data.ToArray());
                    String      characterName = Utils.readNullTerminatedString(dataString, ref offset);
                    int         length        = data.IndexOf(0, offset) - offset;
                    List <byte> stats         = data.GetRange(offset, length);
                    offset += length;
                    OnSetClassByte((byte)((stats[13] - 0x01) & 0xFF));
                    byte   level         = stats[25];
                    byte   flags         = stats[26];
                    bool   hardcore      = (flags & 0x04) != 0;
                    bool   dead          = (flags & 0x08) != 0;
                    bool   expansion     = (flags & 0x20) != 0;
                    String coreString    = hardcore ? "Hardcore" : "Softcore";
                    String versionString = expansion ? "Expansion" : "Classic";

                    if (_character == null && i == 1)
                    {
                        selectFirstCharacter = true;
                        _character           = characterName;
                        UpdateCharacterName(_character);
                    }

                    if (_character.Equals(characterName))
                    {
                        foundCharacter = true;
                        _level         = level;
                    }
                }

                if (!foundCharacter)
                {
                    Logger.Write("Unable to locate character specified");
                    return;
                }

                byte[] packet = Connection.BuildPacket(0x07, System.Text.Encoding.ASCII.GetBytes(_character), Zero);
                Connection.Write(packet);
            }
        }
Example #25
0
 public void MakeGame(Client.GameDifficulty difficulty, String gameName, String gamePass)
 {
     _gameName = gameName;
     _gamePass = gamePass;
     byte[] temp   = { 0x01, 0xff, 0x08 };
     byte[] packet = Connection.BuildPacket(0x03, BitConverter.GetBytes((ushort)(2 * _nextGameIndex)), BitConverter.GetBytes(Utils.GetDifficulty(difficulty)), temp, Encoding.ASCII.GetBytes(_gameName), Zero,
                                            Encoding.ASCII.GetBytes(_gamePass), Zero, Zero);
     Connection.Write(packet);
 }
 void FlushCore(TimeSpan timeout)
 {
     if (pendingWriteSize > 0)
     {
         ThreadTrace.Trace("BC:Flush");
         Connection.Write(writeBuffer, 0, pendingWriteSize, false, timeout);
         pendingWriteSize = 0;
     }
 }
        /// <summary>
        /// Dispatches the command to the client control port and produces a <typeparamref name="T" /> response result.
        /// </summary>
        /// <param name="connection">The control connection where the command should be dispatched.</param>
        /// <returns>
        /// A <typeparamref name="T" /> object instance containing the response data.
        /// </returns>
        protected override CommandResponse Dispatch(Connection connection)
        {
            if (connection.Write("signal newnym"))
            {
                ConnectionResponse response = connection.Read();
                return(new CommandResponse(response.Success));
            }

            return(new CommandResponse(false));
        }
Example #28
0
        protected override void OnSendCore(Message message, TimeSpan timeout)
        {
            bool allowOutputBatching;
            ArraySegment <byte> messageData;

            allowOutputBatching = message.Properties.AllowOutputBatching;
            messageData         = EncodeMessage(message);
            Connection.Write(messageData.Array, messageData.Offset, messageData.Count, !allowOutputBatching,
                             timeout, BufferManager);
        }
Example #29
0
        private void WriteChunk()
        {
            string header = _OutputBufferUsed.ToString("X");

            _Con.WriteAsciiLine(header);

            _Con.Write(_OutputBuffer, _OutputBufferUsed);
            _Con.WriteAsciiEol();
            _OutputBufferUsed = 0;
        }
Example #30
0
        public static void Main(string[] args)
        {
            /* Start application */
            // new Program();
            Connection connection = new Connection("192.168.43.21", 1337);

            while (true)
            {
                connection.Write(Console.ReadLine());
            }
        }
Example #31
0
        //-------------------------------------------------------
        // Private methods.
        //-------------------------------------------------------
        /// <summary>
        /// Issue request and set results buffer. This method is used internally.
        /// The static request methods should be used instead.
        /// </summary>
        /// <param name="conn">socket connection to server node</param>
        /// <exception cref="AerospikeException">if socket send or receive fails</exception>
        private void SendCommand(Connection conn)
        {
            try
            {
                // Write size field.
                ulong size = ((ulong)offset - 8L) | (2L << 56) | (1L << 48);
                ByteUtil.LongToBytes(size, buffer, 0);

                // Write.
                conn.Write(buffer, offset);

                // Read - reuse input buffer.
                conn.ReadFully(buffer, 8);

                size = (ulong)ByteUtil.BytesToLong(buffer, 0);
                length = (int)(size & 0xFFFFFFFFFFFFL);
                ResizeBuffer(length);
                conn.ReadFully(buffer, length);
                offset = 0;
            }
            catch (SocketException se)
            {
                throw new AerospikeException(se);
            }
        }
Example #32
0
 public void Connect()
 {
     _conn = new Connection(this, HandleMessage);
     _conn.Write("NICK {0}", NickName);
     _conn.Write("USER {0} {1} {2} :{3}", NickName, "*", 8, RealName);
 }
Example #33
0
    public static void exchangeData(Connection connection)
    {
        while(true) {
            //client getur ekki lesið á með þetta er ekki að fá neitt
            //string received = connection.Read();

            //string coords = ball.x + "," + ball.y + "," + PlayerScore1  + "," +  PlayerScore2  + "," + paddle1;
            string coords = ball.x+","+ball.y;

            connection.Write(coords);
         	}
    }