Example #1
0
            // rest is ignored

            public Socks4Response(System.Net.Sockets.Socket socket)
            {
                var receiveBuffer = new byte[4];

                // Get the version
                socket.Receive(receiveBuffer, 1, SocketFlags.None);
                Version = receiveBuffer[0];

                // Get the command
                socket.Receive(receiveBuffer, 1, SocketFlags.None);
                Command = receiveBuffer[0];

                // Get the destPort (ignored)
                socket.Receive(receiveBuffer, 2, SocketFlags.None);

                // Get the destAddress (ignored)
                socket.Receive(receiveBuffer, 4, SocketFlags.None);
            }
        /// <summary>
        /// Receives the given amount of bytes into the buffer given a offset and an amount.
        /// </summary>
        /// <param name="buffer">The array to receive into</param>
        /// <param name="offset">The location to receive into</param>
        /// <param name="amount">The 0 based amount of bytes to receive, 0 will have no result</param>
        /// <param name="socket">The socket to receive on</param>
        /// <returns>The amount of bytes recieved which will be equal to the amount paramter unless the data was unable to fit in the given buffer</returns>
        public static int AlignedReceive(byte[] buffer, int offset, int amount, System.Net.Sockets.Socket socket, out System.Net.Sockets.SocketError error)
        {
            //Store any socket errors here incase non-blocking sockets are being used.
            error = System.Net.Sockets.SocketError.SocketError;

            //Return the amount if its negitive;
            if (amount <= 0) return amount;

            //To hold what was received and the maximum amount to receive
            int totalReceived = 0, max = buffer.Length - offset, attempt = 0;

            //Ensure that only max is received
            if (amount > max) amount = max;

            //While there is something to receive
            while (amount > 0)
            {
                lock (socket)
                {
                    //Receive it into the buffer at the given offset taking into account what was already received
                    int justReceived = socket.Receive(buffer, offset, amount, System.Net.Sockets.SocketFlags.None, out error);

                    //decrease the amount by what was received
                    amount -= justReceived;

                    //Increase the offset by what was received
                    offset += justReceived;

                    //Increase total received
                    totalReceived += justReceived;

                    //If nothing was received
                    if (justReceived == 0)
                    {
                        //Try again maybe
                        ++attempt;

                        //Only if the attempts in operations were greater then the amount of bytes requried
                        if (attempt > amount) error = System.Net.Sockets.SocketError.TimedOut;
                    }

                    //Break on offset reaching the max or any error which requires
                    if (offset >= max || error == System.Net.Sockets.SocketError.ConnectionAborted || error == System.Net.Sockets.SocketError.TimedOut || error == System.Net.Sockets.SocketError.ConnectionReset) break;
                }
            }

            return totalReceived;
        }
Example #3
0
        /*
        *********************************************************************************************************
        *                                              ReceiveData()
        *
        * Description : Cette fonction envoie du data sur le socket
        *
        * Argument(s) : s               Le socket de communication
        *               size            Le nombre d'octets à recevoir sur le socket
        *
        * Return(s)   : byte[]          Le tableau d'octets contenant les données reçues
        *********************************************************************************************************
        */
        private static byte[] ReceiveData(System.Net.Sockets.Socket s, int size)
        {
            int total = 0;
            int dataleft = size;
            byte[] data = new byte[size];
            int recv;

            while (total < size)
            {
                recv = s.Receive(data, total, dataleft, 0);
                if (recv == 0)
                {
                    data = Encoding.ASCII.GetBytes("exit ");
                    break;
                }
                total += recv;
                dataleft -= recv;
            }
            return data;
        }
Example #4
0
		/// <summary>
		/// Receives the next avaliable message from the specified queue and assigns a BinaryMessageFormatter to its formatter property.
		/// </summary>
		/// <param name="queue">The queue where to retrieve the message from</param>
		/// <param name="expiration">Specifies a timeout time to return if no message is avaliable</param>
		/// <returns>A message if one is avaliable or null if the timeout is specified and it expires</returns>
		public static System.Messaging.Message ReceiveMessage(System.Messaging.MessageQueue queue, params System.Object[] expiration)
		{
			System.Messaging.Message tempMessage = null;

			if (expiration.Length == 0)
			{
				tempMessage = queue.Receive();
			}
			else
			{
				try
				{
					tempMessage = queue.Receive((System.TimeSpan)expiration[0]);					
				}
				catch (System.Messaging.MessageQueueException e)
				{
					//Check if the exception was caused by the timeout expiration, in this case the method should return null
					if (e.MessageQueueErrorCode != System.Messaging.MessageQueueErrorCode.IOTimeout)
					{						
						throw e;
					}
				}		
			}
			if (tempMessage != null)
			{
				tempMessage.Formatter = new System.Messaging.BinaryMessageFormatter();
			}
			return tempMessage;
		}
 byte[] CommandCheck(System.Net.Sockets.Socket sd, int comm)
 {
     int n1 = 0;
     int n = 0;
     byte[] b = new byte[10001];
     byte[] bs = new byte[8];
     int i = 0;
     while (!(n1 == 8))
     {
         n = sd.Receive(bs, n1, 8 - n1, 0);
         n1 = n1 + n;
     }
     Array.ConstrainedCopy(bs, 0, b, 0, n);
     n1 = 0;
     while (!(n1 == 8))
     {
         n = sd.Receive(bs, n1, 8 - n1, 0);
         n1 = n1 + n;
     }
     Array.ConstrainedCopy(bs, 0, b, 8, n);
     i = bs[0] + bs[1] * (256);
     n1 = 0;
     while (!(n1 == i))
     {
         n = sd.Receive(b, 16 + n1, i - n1, 0);
         n1 = n1 + n;
     }
     string s = HexString(b, 16 + n, 0);
     if (s.Contains("1b 0 4 0") == true) { TTTest(sd); return CommandCheck(sd, comm); }
     if (b[36] != comm)
     {
         if (b[36] == 0x1b) { Log.Debug("MMSDownloader : Performing Network Timing Test"); TTTest(sd); }
         if (b[36] == 0x15) { Log.Debug("MMSDownloader : Validating Network Connection..."); return CommandCheck(sd, comm); }
     }
     return b;
     /*if ((n > i) == true)
     {
         Console.WriteLine("");
         int z = 0;
         while (!(n == 0))
         {
             n = sd.Receive(b, 16 + i + 1 + z, 2, 0);
             z = z + n;
         }
         s = HexString(b, 16 + i + 1 + n, 0);
         Console.WriteLine(16 + i + 1 + z);
     }
     if (i * 4 < 40)
     {
         Console.WriteLine(i);
         while (!(n == 0))
         {
             n = sd.Receive(b, 16 + i, i, 0);
             if (n > 0)
                 Console.WriteLine("HUH?");
         }
     }*/
 }
 int ReturnB2(System.Net.Sockets.Socket sd)
 {
     int n = 0;
     byte[] bs = new byte[8];
     int i = 0;
     int n1 = 0;
     while (!(n1 == 8))
     {
         n = sd.Receive(bs, n1, 8 - n1, 0);
         n1 = n1 + n;
     }
     i = (int)(bs[0] + bs[1] * 256 + bs[2] * 4096 + bs[3] * (Math.Pow(16, 4)));
     byte[] b = new byte[i + 8];
     Array.ConstrainedCopy(bs, 0, b, 0, n);
     n = sd.Receive(b, 8, i, 0);
     string s = HexString(b, 8 + n, 0);
     if (s.Contains("1E 0 4 0"))
         return 1;
     if (s.Contains("1B 0 4 0"))
         return 2;
     throw new Exception("Error");
 }
 byte[] ReturnB(System.Net.Sockets.Socket sd)
 {
     int n = 0;
     byte[] b = new byte[10001];
     byte[] bs = new byte[8];
     int i = 0;
     int n1 = 0;
     while (!(n1 == 8))
     {
         n = sd.Receive(bs, n1, 8 - n1, 0);
         n1 = n1 + n;
     }
     Array.ConstrainedCopy(bs, 0, b, 0, n);
     n1 = 0;
     while (!(n1 == 8))
     {
         n = sd.Receive(bs, n1, 8 - n1, 0);
         n1 = n1 + n;
     }
     Array.ConstrainedCopy(bs, 0, b, 8, n);
     i = bs[0] + bs[1] * (256);
     n1 = 0;
     while (!(n1 == i))
     {
         n = sd.Receive(b, 16 + n1, i - n1, 0);
         n1 = n1 + n;
     }
     byte[] c = new byte[16 + i];
     Array.ConstrainedCopy(b, 0, c, 0, 16 + i);
     return c;
 }
 void WriteStream(System.Net.Sockets.Socket sd, string path, decimal time, int hsize)
 {
     int p = 0;
     int np = 0;
     long rp = 0;
     FileStream fs = null;
     bool fe = File.Exists(path);
     fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
     byte[] P5B1 = { 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0xac, 0x40, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
     byte[] rb = null;
     if (fe == true)
     {
         rb = new byte[fs.Length];
         fs.Read(rb, 0, rb.Length);
         p = GetPacketLength(rb);
         np = GetNumberOfPackets(rb);
         rp = (fs.Length - hsize) / p;
         decimal rtime = default(decimal);
         rtime = ((rp) / np) * time;
         byte[] br = HexDoublePercision(rtime);
         Array.ConstrainedCopy(br, 0, P5B1, 8, 8);
     }
     Log.Debug("MMSDownloader : Requesting Media Header...");
     sd.Send(HPacket(0x15, P5B1, null));
     int n = 0;
     int n1 = 0;
     byte[] bs = new byte[8];
     int i = 0;
     int cur = 0;
     int sp = 0;
     byte[] b = ReturnB(sd);
     if (fe == true)
         fs.Position = 0;
     if (b[36] == 0x11)
     {
     more:
         n1 = 0;
         while (!(n1 == 8))
         {
             n = sd.Receive(bs, n1, 8 - n1, 0);
             n1 = n1 + n;
         }
         Array.ConstrainedCopy(bs, 0, b, 0, n);
         i = bs[6] + bs[7] * (256) - 8;
         string s = HexString(bs, 0, 0);
         cur = cur + i;
         Log.Debug("MMSDownloader : Header Size: " + cur + "Bytes");
         byte[] header = new byte[i];
         n1 = 0;
         while (!(n1 == i))
         {
             n = sd.Receive(header, n1, i - n1, 0);
             n1 = n1 + n;
         }
         if (fe == true)
         {
             if (Find(header, rb) == -1)
                 Log.Debug("MMSDownloader : ERROR! Files Dont Match!");
             //: Exit Sub
         }
         if (p == 0)
             p = GetPacketLength(header);
         if (np == 0)
             np = GetNumberOfPackets(header);
         fs.Write(header, 0, header.Length);
         if (bs[5] == 0x4 | bs[5] == 0x8)
         {
             goto more;
         }
     }
     if (fe == true)
         fs.Position = fs.Length - 1;
     Log.Debug("MMSDownloader : Header Recieved And Written...Requesting Media...");
     byte[] P6B1 = { 0x1, 0x0, 0x0, 0x0, 0xff, 0xff, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
     sd.Send(HPacket(0x7, P6B1, null));
     byte[] b2 = ReturnB(sd);
     cur = 0;
     if (b2[36] == 0x21)
     {
         byte[] b3 = ReturnB(sd);
         if (b3[36] == 0x5)
         {
             n1 = 0;
             while (!(n1 == 8))
             {
                 n = sd.Receive(bs, n1, 8 - n1, 0);
                 n1 = n1 + n;
             }
             i = bs[6] + bs[7] * (256);
             i = i - 8;
             string s = null;
             s = HexString(bs, 8, 0);
             byte[] buffer = new byte[p];
             do
             {
                 n1 = 0;
                 while (!(n1 == i))
                 {
                     n = sd.Receive(buffer, n1, i - n1, 0);
                     n1 = n1 + n;
                 }
                 if (fe == true)
                 {
                     if (Find(buffer, rb) > -1)
                     {
                         sp = sp + 1;
                         Log.Debug("MMSDownloader : skipped: " + sp);
                         goto skip;
                     }
                     else
                     {
                         fe = false;
                     }
                 }
                 s = HexString(buffer, 0, 0);
                 if (s.Contains("1B 0 4 0") == true)
                     Log.Debug("MMSDownloader : !!!!");
                 fs.Write(buffer, 0, p);
                 cur = cur + p;
                 PercentDownloaded = (byte)((float)rp / np * 100f);
                 CurrentBytesDownloaded = cur;
                 Log.Debug("MMSDownloader : Recieving Packets. Packet Size Is " + p + "." + Environment.NewLine + "Recieved " + rp + " Packets Out Of " + np + "." + Environment.NewLine + "Downloaded So Far " + cur + "Bytes.");
             skip:
                 n1 = 0;
                 int b1 = 0;
                 while (!(n1 == 8))
                 {
                     n = sd.Receive(bs, n1, 8 - n1, 0);
                     if (n == 0)
                         b1 = b1 + 1;
                     if (b1 > 0)
                         Log.Debug("MMSDownloader : " + b1);
                     n1 = n1 + n;
                 }
                 string s1 = HexString(bs, 0, 0);
                 if (s1.Contains("CE FA B B0") == true)
                 {
                     do
                     {
                         int x = ReturnB2(sd);
                         if (x == 1)
                         {
                             Log.Debug("MMSDownloader : Download Is Complete!"); return;
                         }
                         if (x == 2)
                         {
                             Log.Debug("MMSDownloader : Sending Network Timing Test..");
                             TTTest(sd);
                             n1 = 0;
                             while (!(n1 == 8))
                             {
                                 n = sd.Receive(bs, n1, 8 - n1, 0);
                                 n1 = n1 + n;
                             }
                         }
                     } while (!(HexString(bs, 8, 0).Contains("CE FA B B0") == false));
                 }
                 i = bs[6] + bs[7] * (256) - 8;
                 rp = rp + 1;
             } while (true);
         }
     }
 }
Example #9
0
        public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count,int min)
        {
            // Returns 0 bytes if not enough space in target
            if (target.Length == 0)
                return 0;

           
            int bytesRead, totalBytesRead = 0, buffStart = start;
            
            while (true)
            {
                try
                {
                    if (!sock.Connected)
                        throw new ExtSocketException("socket closed");

                    bytesRead = sock.Receive(target, start, count, SocketFlags.None);

                    if (bytesRead == 0) throw new ExtSocketException("socket closed");

                    totalBytesRead += bytesRead;
                    if (bytesRead == count) break;
                    else
                        count = count - bytesRead;

                    start = start + bytesRead;
                    if (totalBytesRead >min &&  sock.Available <= 0) break;
                }
                catch (SocketException e)
                {

                    if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue;

                    else throw;
                }

            }

            // Returns -1 if EOF
            if (totalBytesRead == 0)
                return -1;

           

            return totalBytesRead;
        }
Example #10
0
        /* ----------------------------------------------------------------------------------------------------------------------------------------------- */
        /**
         *  @brief    server loop which waits for data from robot and answers with XML File
         *
         *  @retval   none
         */
        /* ----------------------------------------------------------------------------------------------------------------------------------------------- */
        private void robotServerLoop(System.Net.Sockets.Socket comHandler)
        {
            // variable declarations
            byte[] localIncomingDataByteBuffer;                           // data buffer for incoming data
            byte[] localReceivedFullMessageBytes;
            byte[] sendMessage;
            int bytesReceived;
            String localCommandString;
            String localInfoString;

            // variable initializations

            localReceivedFullMessageBytes = null;
            sendMessage = new Byte[2048];

            // set state to running
            setRobotConnectionState(ConnectionState.running);

            // --------------------------------------------------
            // now lets start the endles loop
            // --------------------------------------------------
            while (true)
            {
                // reset and start the stopwatch to measure the time between two robot info cycles
                stopWatch_.Reset();
                stopWatch_.Start();

                // command the garbage collector to collect at the beginning of each cycle
                System.GC.Collect();

                // signal to the connected application that the command data is ready to be modified
                nextCycleStarted_ = true;

                // ------------------------------------------------------------
                // wait for data and receive bytes
                // ------------------------------------------------------------
                try
                {
                    while (patternFound_ == false)
                    {
                        String testString;

                        localIncomingDataByteBuffer = new Byte[2048];                 // load byte buffer with instance

                        bytesReceived = comHandler.Receive(localIncomingDataByteBuffer);
                        if (bytesReceived == 0)
                        {
                            makeLoggingEntry("client closed connection (bytesReceived=0)");
                            setRobotConnectionState(ConnectionState.closing);
                            break; // client closed socket
                        }

                        testString = System.Text.Encoding.ASCII.GetString(localIncomingDataByteBuffer, 0, bytesReceived);

                        // start stopwatch for receiving task
                        stopWatchReceive_.Reset();
                        stopWatchReceive_.Start();

                        // fill the received bytes into the local buffer and check if a full message came from robot
                        localReceivedFullMessageBytes = giveRightByteArray(localIncomingDataByteBuffer, bytesReceived);
                    }

                    // increment the packages counter
                    receivedPackagesCount_++;

                    // clear the pattern found flag
                    patternFound_ = false;
                }
                catch
                {
                    makeLoggingEntry("connection closed from remote host...\n\r");
                    setRobotConnectionState(ConnectionState.closing);
                    break;
                }

                stopWatchReceive_.Stop();

                stopWatchSend_.Reset();
                stopWatchSend_.Start();

                // -------------------------------------------------------------------------------------
                // signals the connector that the sending operation just started =>
                // the external system has to wait until this variable goes again to true
                // -------------------------------------------------------------------------------------
                nextCycleStarted_ = false;

                // --------------------------------------------------------------
                // only try to load the xml stuff when there is data available
                // --------------------------------------------------------------
                if (localReceivedFullMessageBytes != null)
                {
                    // -------------------------------------------------------------------------
                    // check if the string is valid and then save it to the locally xml storage
                    // -------------------------------------------------------------------------
                    if (checkReceivedMessage(localReceivedFullMessageBytes) == true)
                    {
                        try
                        {
                            // check if there is synchron AKorr active
                            doSynchronAKorr();

                            // check if there is synchron RKorr active
                            doSynchronRKorr();

                            // get the sendString variable under mutex protection from getter method
                            localCommandString = getCommandString();

                            // get the receiveString variable under mutex protection from getter method
                            localInfoString = getRobotInfoString();

                            // mirror the IPO counter you received yet
                            localCommandString = mirrorInterpolationCounter(localInfoString, localCommandString);

                            // get bytes out of string
                            sendMessage = System.Text.Encoding.ASCII.GetBytes(localCommandString);

                            // send data to robot
                            comHandler.Send(sendMessage, 0, sendMessage.Length, System.Net.Sockets.SocketFlags.None);

                            sendPackagesCount_++;

                            // copy the edited string under mutex protection back
                            setCommandString(localCommandString);
                        }
                        catch
                        {
                            makeLoggingEntry("could not send XML string");
                        }
                    }
                }

                stopWatchSend_.Stop();

                stopWatch_.Stop();
                communicationTimeMilliSeconds_ = stopWatch_.ElapsedMilliseconds;
                communicationTimeTicks_ = stopWatch_.ElapsedTicks;

                // ----------------------------------------------------------------------------------------------
                // count the delayed packages
                // ----------------------------------------------------------------------------------------------
                if (communicationTimeMilliSeconds_ > 16)
                {
                    delayedPackagesCount_++;
                    delayedPackagesMilliSecondsComm_ = communicationTimeMilliSeconds_;
                    delayedPackagesMilliSecondsSend_ = stopWatchSend_.ElapsedTicks;
                    delayedPackagesTicksComm_ = stopWatch_.ElapsedTicks;
                    delayedPackagesMilliSecondsReceive_ = stopWatchReceive_.ElapsedTicks;
                }

                // ----------------------------------------------------------------------------------------------
                // close communication channel to robot if state changed to closing
                // ----------------------------------------------------------------------------------------------
                if ((getRobotConnectionState() == ConnectionState.closeRequest) ||(getRobotConnectionState() == ConnectionState.closing) )
                {
                    setRobotConnectionState(ConnectionState.closing);
                    break;
                }
            }
        }
Example #11
0
        /// <summary>
        /// Does the video job.
        /// </summary>
        private void DoWorkerJob(System.Net.Sockets.UdpClient socket, int data_port)
        {
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, data_port);
            try
            {
                // loop until we get an exception eg the socket closed
                while (true)
                {
                    byte[] frame = socket.Receive(ref ipEndPoint);

                    // We have an RTP frame.
                    // Fire the DataReceived event with 'frame'
                    Console.WriteLine("Received RTP data on port " + data_port);

                    Rtsp.Messages.RtspChunk currentMessage = new Rtsp.Messages.RtspData();
                    // aMessage.SourcePort = ??
                    currentMessage.Data = frame;
                    ((Rtsp.Messages.RtspData)currentMessage).Channel = data_port;

                    OnDataReceived(new Rtsp.RtspChunkEventArgs(currentMessage));

                }
            }
            catch (ObjectDisposedException)
            {
            }
            catch (SocketException)
            {
            }
        }
Example #12
0
        public int CompleteFrom(System.Net.Sockets.Socket socket, Common.MemorySegment buffer)
        {
            if (IsComplete) return 0;

            int contained = m_Packet.Length,
                needed = MessageLength - contained - HeaderLength, recieved = 0;

            int r = buffer.Offset;

            while (needed > 0)
            {
                r += socket.Receive(buffer.Array, r, needed, System.Net.Sockets.SocketFlags.None);
                needed -= r;
                recieved += r;
            }

            m_Packet = m_Packet.Concat(buffer).ToArray();

            return recieved;
        }
Example #13
0
        /// <summary>
        /// Returns a UDP datagram that was sent by a remote host.
        /// </summary>
        /// <param name="tempClient">UDP client instance to use to receive the datagram</param>
        /// <param name="packet">Instance of the recieved datagram packet</param>
        public static void Receive(System.Net.Sockets.UdpClient tempClient, out PacketSupport packet)
        {
            System.Net.IPEndPoint remoteIpEndPoint =
                new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);

            PacketSupport tempPacket;
            try
            {
                byte[] data_in = tempClient.Receive(ref remoteIpEndPoint);
                tempPacket = new PacketSupport(data_in, data_in.Length);
                tempPacket.IPEndPoint = remoteIpEndPoint;
            }
            catch ( System.Exception e )
            {
                throw new System.Exception(e.Message);
            }
            packet = tempPacket;
        }