Example #1
0
        async Task <Job> StartDD(CancellationToken cancellationToken)
        {
            // integration tests may take a while to release the port
            using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            cts.CancelAfter(TimeSpan.FromMinutes(1));
            while (true)
            {
                try
                {
                    SocketExtensions.BindTest(IntegrationTest.DDPort, false);
                    break;
                }
                catch
                {
                    try
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1), cts.Token);

                        continue;
                    }
                    catch (OperationCanceledException)
                    {
                    }

                    throw;
                }
            }
            await Task.Delay(TimeSpan.FromSeconds(3), cts.Token);

            return(await instanceClient.DreamDaemon.Start(cancellationToken));
        }
Example #2
0
        public void Connect(string host, ushort port)
        {
            try
            {
                Disconnect();
                Initialize();

                _handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SocketExtensions.SetKeepAliveEx(_handle, KEEP_ALIVE_INTERVAL, KEEP_ALIVE_TIME);
                _handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
                _handle.NoDelay = true;

                _handle.Connect(host, port);

                if (_handle.Connected)
                {
                    _handle.BeginReceive(this._buffer, 0, this._buffer.Length, SocketFlags.None, AsyncReceive, null);
                    OnClientState(true);
                }
            }
            catch (Exception ex)
            {
                OnClientFail(ex);
                Disconnect();
            }
        }
Example #3
0
            async Task AcceptAsync(Socket socket)
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();

                args.Completed += (s, a) => SocketExtensions.Complete(s, a, false, a.SocketError == SocketError.Success ? a.AcceptSocket : null);

                while (!this.closed)
                {
                    try
                    {
                        args.AcceptSocket = null;
                        Socket acceptSocket = await socket.AcceptAsync(args, SocketFlags.None);

                        if (acceptSocket != null)
                        {
                            var task = this.HandleSocketAsync(acceptSocket);
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        // listener is closed
                    }
                    catch (Exception exception)
                    {
                        Trace.WriteLine(TraceLevel.Warning, exception.ToString());
                    }
                }

                args.Dispose();
                socket.Dispose();
            }
Example #4
0
            public void Run()
            {
                Socket  socket    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Boolean connected = false;

                try
                {
                    if (portScannerManager.timeout == TimeSpan.Zero)
                    {
                        socket.Connect(portScannerManager.hostIP, port);
                        connected = true;
                    }
                    else
                    {
                        if (SocketExtensions.ConnectWithTimeout(socket, new IPEndPoint(portScannerManager.hostIP, port), portScannerManager.timeout))
                        {
                            connected = true;
                        }
                    }
                }
                catch (SocketException)
                {
                }
                finally
                {
                    if (socket != null)
                    {
                        if (socket.Connected)
                        {
                            try { socket.Shutdown(SocketShutdown.Both); }
                            catch (SocketException) { }
                        }
 private void Asistente_de_conexion_Load(object sender, EventArgs e)
 {
     this.CenterToParent();
     foreach (var cli in clientes)
     {
         if (SocketExtensions.IsConnected(cli) == true)
         {
             listBox1.Items.Add("📱=" + cli.Client.RemoteEndPoint.ToString());
         }
     }
     if (GR3_UiF.Properties.Settings.Default.lenguaje == "spa")
     {
         this.label1.Text = "para conectar al servidor introduce:";
         this.label3.Text = "O escanea el siguiente codigo";
         this.label4.Text = "Clientes conectados:";
     }
     if (GR3_UiF.Properties.Settings.Default.lenguaje == "eng")
     {
         this.label1.Text = "To connect to server enter:";
         this.label3.Text = "Or scan the following code";
         this.label4.Text = "Connected clients:";
     }
     label2.Text       = ip;
     pictureBox1.Image = GetQRCode();
 }
        public override string GenerateSDPDescription()
        {
            StringBuilder sb = new StringBuilder();

            TimeVal timeVal = new TimeVal();

            RTPTime.GetTimestamp(ref timeVal);

            sb.Append("v= 0\r\n").
            AppendFormat("o=- {0}{1:06} 1 IN IP4 {2}\r\n", timeVal.tv_sec, timeVal.tv_usec, SocketExtensions.GetLocalIPV4Address()).
            AppendFormat("s=Session streamed by \"{0}\"\r\n", RTSPServer.ServerVersion).
            AppendFormat("i={0}\r\n", Name).
            Append("t=0 0\r\n").
            AppendFormat("a=tool:{0}\r\n", RTSPServer.ServerVersion).
            Append("a=type:broadcast\r\n").
            Append("a=control:*\r\n").
            AppendFormat("a=source-filter: incl IN IP4 * {0}\r\n", SocketExtensions.GetLocalIPV4Address()).
            Append("a=rtcp-unicast: reflection\r\n").
            Append("a=range:npt=0-\r\n").
            AppendFormat("a=x-qt-text-nam:Session streamed by {0}\r\n", RTSPServer.ServerVersion).
            AppendFormat("a=x-qt-text-inf:{0}\r\n", Name).
            AppendFormat("m=video {0} RTP/AVP 96\r\n", ServerRTPPort).
            AppendFormat("c=IN IP4 {0}/255\r\n", MulticastAdress).
            Append("b=AS:500\r\n").
            Append("a=rtpmap:96 H264/90000\r\n").
            Append("a=fmtp:96 packetization-mode=1;profile-level-id=640028;sprop-parameter-sets=J2QAKKwrQCgC3QDxImo=,KO4Pyw==\r\n").
            Append("a=control:track1\r\n");

            return(sb.ToString());
        }
        public void InitSendClientPassive()
        {
            bool SendClosed = false;

            while (true)
            {
                if (ConnectionClosed != null && SendClosed)
                {
                    SendClosed = false;
                    context.Post(delegate { ConnectionClosed(1); }, null);
                }



                if (Send_Client == null || Send_Client.Connected == false)
                {
                    if (Send_Client != null)
                    {
                        Send_Client.Close();
                    }

                    TcpListener server = new TcpListener(local_ip, send_connection_port);
                    server.Start();

                    Send_Client = null;
                    if (onlyOneConnection)
                    {
                        Recieve_Client = null;
                    }
                    Send_Client = server.AcceptTcpClient();

                    SocketExtensions.SetKeepAlive(Send_Client.Client, 100, 20);

                    SendClosed = true;

                    if (ConnectionEstablished != null)
                    {
                        context.Post(delegate { ConnectionEstablished(1); }, null);
                    }

                    //Thread for Recieving Data
                    if (ReceiveDataSendClientThread != null)
                    {
                        ReceiveDataSendClientThread.Abort();
                        Threads.Remove(ReceiveDataSendClientThread);
                    }
                    ReceiveDataSendClientThread      = new Thread(ReceiveDataSendClient);
                    ReceiveDataSendClientThread.Name = "PReceiveDataSendClientThread";
                    ReceiveDataSendClientThread.Start();
                    Threads.Add(ReceiveDataSendClientThread);
                    //End Thread

                    if (onlyOneConnection)
                    {
                        Recieve_Client = Send_Client;
                    }
                }
            }
        }
Example #8
0
        /// <inheritdoc />
        public async Task <ushort?> GetAvailablePort(ushort basePort, bool checkOne, CancellationToken cancellationToken)
        {
            logger.LogTrace("Port allocation >= {0} requested...", basePort);

            var ddPorts = await databaseContext
                          .DreamDaemonSettings
                          .AsQueryable()
                          .Select(x => x.Port)
                          .ToListAsync(cancellationToken)
                          .ConfigureAwait(false);

            var dmPorts = await databaseContext
                          .DreamMakerSettings
                          .AsQueryable()
                          .Select(x => x.ApiValidationPort)
                          .ToListAsync(cancellationToken)
                          .ConfigureAwait(false);

            var    exceptions = new List <Exception>();
            ushort I          = 0;

            try
            {
                for (I = basePort; I < UInt16.MaxValue; ++I)
                {
                    if (checkOne && I != basePort)
                    {
                        break;
                    }

                    if (I == serverPortProvider.HttpApiPort ||
                        ddPorts.Contains(I) ||
                        dmPorts.Contains(I))
                    {
                        continue;
                    }

                    try
                    {
                        SocketExtensions.BindTest(I, false);
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex);
                        continue;
                    }

                    logger.LogInformation("Allocated port {0}", I);
                    return(I);
                }

                logger.LogWarning("Unable to allocate port >= {0}!", basePort);
                return(null);
            }
            finally
            {
                logger.LogDebug(new AggregateException(exceptions), "Failed to allocate ports {0}-{1}!", basePort, I - 1);
            }
        }
Example #9
0
        public void InitSendClientPassive()
        {
            TcpListener server       = null;
            TcpClient   oldTcpClient = null;
            bool        SendClosed   = false;

            while (true)
            {
                if (ConnectionClosed != null && SendClosed && (_tcpClient == null || _tcpClient.Connected == false))
                {
                    oldTcpClient = _tcpClient;
                    SendClosed   = false;
                    context.Post(delegate { ConnectionClosed(oldTcpClient); }, null);
                }

                if (!SendClosed && (_tcpClient == null || _tcpClient.Connected == false))
                {
                    if (_tcpClient != null)
                    {
                        _tcpClient.Close();
                    }

                    if (server == null)
                    {
                        server = new TcpListener(/*local_ip,*/ _port);
                        server.Start();
                    }

                    _tcpClient = null;
                    _tcpClient = server.AcceptTcpClient();
                    SocketExtensions.SetKeepAlive(_tcpClient.Client, 100, 20);
                    SendClosed = true;

                    if (ConnectionEstablished != null)
                    {
                        context.Post(delegate { ConnectionEstablished(_tcpClient); }, null);
                    }

                    //Thread for Recieving Data
                    if (_receiveDataThread != null)
                    {
                        _receiveDataThread.Abort();
                        Threads.Remove(_receiveDataThread);
                    }
                    _receiveDataThread      = new Thread(ReceiveDataSendClient);
                    _receiveDataThread.Name = "PReceiveDataSendClientThread";
                    _receiveDataThread.Start();
                    Threads.Add(_receiveDataThread);
                    //End Thread
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
Example #10
0
        public MediaRtspServer(int port)
        {
            IPAddress serverIp = SocketExtensions.GetFirstUnicastIPAddress(System.Net.Sockets.AddressFamily.InterNetwork);

            _server = new RtspServer(serverIp, 6601)
            {
                Logger = new RtspServerConsoleLogger(),
                //ClientSessionLogger = new Media.Rtsp.Server.RtspServerDebugLogger()
            };
        }
Example #11
0
        public virtual int CompleteFrom(System.Net.Sockets.Socket socket, MemorySegment buffer)
        {
            if (IsReadOnly)
            {
                throw new InvalidOperationException("Cannot modify a RtcpPacket when IsReadOnly is false.");
            }

            //If the packet is complete then return
            if (IsDisposed || IsComplete)
            {
                return(0);
            }

            //Needs to account for buffer or socket.

            //Calulcate the amount of octets remaining in the RtcpPacket including the header
            int octetsRemaining = ((ushort)(Header.LengthInWordsMinusOne + 1)) * 4 - Length, offset = Payload != null ? Payload.Count : 0;

            if (octetsRemaining > 0)
            {
                //There is not enough room in the array to finish the packet
                if (Payload.Count < octetsRemaining)
                {
                    //Allocte the memory for the required data
                    if (m_OwnedOctets == null)
                    {
                        m_OwnedOctets = new byte[octetsRemaining];
                    }
                    else
                    {
                        m_OwnedOctets = m_OwnedOctets.Concat(new byte[octetsRemaining]).ToArray();
                    }
                }

                System.Net.Sockets.SocketError error;

                int recieved = 0;

                //Read from the stream, decrementing from octetsRemaining what was read.
                while (octetsRemaining > 0)
                {
                    int rec = SocketExtensions.AlignedReceive(m_OwnedOctets, offset, octetsRemaining, socket, out error);
                    offset          += rec;
                    octetsRemaining -= rec;
                    recieved        += rec;
                }

                //Re-allocate the segment around the received data. //length + received
                Payload = new MemorySegment(m_OwnedOctets, 0, m_OwnedOctets.Length);

                return(recieved);
            }

            return(0);
        }
Example #12
0
        public async Task <bool> Play(RTSPRequestParser parser)
        {
            string stream = parser.Media;


            ServerMediaSession session = _connection.Server.lookupServerMediaSession(stream);

            if (session == null)
            {
                _connection.HandleNotFound(parser);
                return(false);
            }
            // Look up information for the specified subsession (track):
            ServerMediaSubsession subsession;

            subsession = session.LookupSubSession(stream);
            ushort rtpSeqNum    = 0;
            uint   rtpTimestamp = 0;

            _rtpStream = subsession.GetStreamInstance();

            rtpSeqNum    = _rtpStream.CurrentSeqNo();
            rtpTimestamp = _rtpStream.CurrentTimeStamp();            // presetNextTimestamp();
            Playing      = true;

            await _rtpStream.AddDestination(this, _destinations);

            if (_destinations.isTCP)
            {
                _connection.RegisterFilter(_rtpStream);
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("RTSP/1.0 200 OK\r\n");
            sb.AppendFormat("Server: {0}\r\n", RTSPServer.ServerVersion);
            sb.AppendFormat("Cseq: {0}\r\n", parser.Headers["CSEQ"]);
            sb.AppendFormat("Session: {0}\r\n", parser.Headers["SESSION"]);
            sb.Append("Last-Modified: Tue, 30 Aug 2016 01:33:17 GMT\r\n");
            sb.Append("Cache-Control: must-revalidate\r\n");
            sb.Append("Date: Sat, 22 Dec 2018 16:18:03 GMT\r\n");
            sb.Append("Expires: Sun, 23 Dec 2018 12:01:28 GMT\r\n");
            sb.Append("Range: npt=0.000-\r\n").
            AppendFormat("RTP-Info: url=rtsp://{0}:{1}/{2}/track1;seq={3};rtptime={4}\r\n\r\n",
                         SocketExtensions.GetLocalIPV4Address(),
                         _connection.Server.Port,
                         subsession.Name,
                         rtpSeqNum, rtpTimestamp);

            string reply = sb.ToString();

            _connection.SendResponse(reply);
            return(true);
        }
Example #13
0
 private void formsincronizacion_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (c != null && SocketExtensions.IsConnected(c))
     {
         c.Client.Send(Encoding.UTF8.GetBytes("desconectarse$  "));
         c.Client.Disconnect(false);
     }
     if (c2 != null && SocketExtensions.IsConnected(c2))
     {
         c2.Client.Disconnect(false);
     }
     detenedor = false;
 }
        public void InitRecieveClientActive()
        {
            bool RecieveClosed = false;

            while (true)
            {
                try
                {
                    if (Recieve_Client == null || Recieve_Client.Connected == false)
                    {
                        if (RecieveClosed)
                        {
                            RecieveClosed = false;
                            context.Post(delegate { ConnectionClosed(2); }, null);
                        }

                        Recieve_Client = null;
                        Recieve_Client = new TcpClient(plc_ip.ToString(), recieve_connection_port);
                        SocketExtensions.SetKeepAlive(Recieve_Client.Client, 100, 20);

                        RecieveClosed = true;

                        if (ConnectionEstablished != null)
                        {
                            context.Post(delegate { ConnectionEstablished(2); }, null);
                        }

                        //Thread for Recieving Data
                        if (ReceiveDataRecieveClientThread != null)
                        {
                            ReceiveDataRecieveClientThread.Abort();
                            Threads.Remove(ReceiveDataRecieveClientThread);
                        }
                        ReceiveDataRecieveClientThread      = new Thread(ReceiveDataRecieveClient);
                        ReceiveDataRecieveClientThread.Name = "AReceiveDataRecieveClient";
                        ReceiveDataRecieveClientThread.Start();
                        Threads.Add(ReceiveDataRecieveClientThread);
                        //End Thread
                    }
                    Thread.Sleep(1000);
                }
                catch (ThreadAbortException ex)
                {
                    return;
                }
                catch (Exception ex)
                {
                    Thread.Sleep(5000);
                }
            }
        }
        private bool Describes(RTSPRequestParser parser)
        {
            // Begin by looking up the "ServerMediaSession" object for the specified "urlTotalSuffix":
            string media = parser.Media;


            ServerMediaSession session = Server.lookupServerMediaSession(media);

            if (session == null)
            {
                HandleNotFound(parser);
                return(false);
            }

            // Look up information for the specified subsession (track):
            ServerMediaSubsession subsession;

            media      = media.TrimEnd('/');       // parser.Uri.Segments[2].TrimStart('/');
            subsession = session.LookupSubSession(media);

            var sdp = subsession.GenerateSDPDescription();


            StringBuilder sb = new StringBuilder();

            sb.Append("RTSP/1.0 200 OK\r\n");
            sb.AppendFormat("Server: {0}\r\n", RTSPServer.ServerVersion);
            sb.AppendFormat("Cseq: {0}\r\n", parser.Headers["CSEQ"]);
            sb.Append("Last-Modified: Tue, 30 Aug 2016 01:33:17 GMT\r\n");
            sb.Append("Cache-Control: must-revalidate\r\n");

            sb.AppendFormat("Content-length: {0}\r\n", sdp.Length);

            sb.Append("Date: Sat, 22 Dec 2018 16:18:03 GMT\r\n");
            sb.Append("Expires: Sat, 22 Dec 2018 16:18:03 GMT\r\n");
            sb.Append("Content-Type: application/sdp\r\n").
            Append("x-Accept-Retransmit: our-retransmit\r\n").
            Append("x-Accept-Dynamic-Rate: 1\r\n").
            AppendFormat("Content-Base: rtsp://{0}:{1}/{2}\r\n\r\n", SocketExtensions.GetLocalIPV4Address(), Server.Port, subsession.Name).
            Append(sdp);

            var str = sb.ToString();

            SendResponse(str);
            return(true);
        }
Example #16
0
        private void StartListeners()
        {
            List <ISocketListener> listeners = new List <ISocketListener>();

            var config = appServer.config;

            if (config.listenerConfigs == null || 0 >= config.listenerConfigs.Count)
            {
                throw new Exception("Listener list wrong");
            }

            for (int index = 0; index < config.listenerConfigs.Count; ++index)
            {
                var listenerConfig = config.listenerConfigs[index];
                if (listenerConfig == null)
                {
                    throw new Exception($"Listener({index}) is null");
                }

                if (string.IsNullOrEmpty(listenerConfig.ip))
                {
                    throw new Exception($"Listener({index}) ip is invalid");
                }

                if (0 >= listenerConfig.port)
                {
                    throw new Exception($"Listener({index}) port is invalid");
                }

                var endPoint = new IPEndPoint(SocketExtensions.ParseIPAddress(listenerConfig.ip), listenerConfig.port);

                var listenerInfo = new ListenerInfo(endPoint, listenerConfig.backlog);

                var socketListener = CreateListener(listenerInfo);
                socketListener.accepted += new ISocketListener.AcceptHandler(OnSocketAccepted);
                socketListener.error    += new ISocketListener.ErrorHandler(OnListenerError);

                socketListener.Start();
            }

            this.listeners = listeners;
        }
        private void InitView()
        {
            Content = new StackLayout()
            {
                Padding  = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0),
                Children =
                {
                    new ListenerBindView(11000,                                 this)
                    {
                        StartListeningTapped = async i =>
                        {
                            Debug.WriteLine("Going to listen on {0}",           i);
                            await _listener.StartListeningAsync(i,              Global.DefaultCommsInterface);
                            _canceller = new CancellationTokenSource();
                            return(true);
                        },
                        StopListeningTapped = async() =>
                        {
                            Debug.WriteLine("Stopping Listening");
                            await _listener.StopListeningAsync();
                            _canceller.Cancel();
                        }
                    },
                    new MessagesView(_messagesObs,                              true)
                    {
                        SendData = async s =>
                        {
                            var sendTasks = _clients.Select(c => SocketExtensions.WriteStringAsync(c,s)).ToList();
                            await Task.WhenAll(sendTasks);

                            return(new Message
                            {
                                Text = s,
                                DetailText =
                                    String.Format("Sent to {0} clients at {1}", sendTasks.Count,
                                                  DateTime.Now.ToString("HH:mm:ss"))
                            });
                        }
                    }
                }
            };
        }
Example #18
0
        internal Client(Server server, Socket sock, Type[] packets)
        {
            try
            {
                AddTypesToSerializer(typeof(IPacket), packets);
                _parentServer = server;
                Initialize();

                _handle = sock;

                SocketExtensions.SetKeepAliveEx(_handle, KEEP_ALIVE_INTERVAL, KEEP_ALIVE_TIME);

                _handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
                _handle.NoDelay = true;

                _handle.BeginReceive(this._buffer, 0, this._buffer.Length, SocketFlags.None, AsyncReceive, null);
                EndPoint = (IPEndPoint)_handle.RemoteEndPoint;
                OnClientState(true);
            }
            catch
            {
                Disconnect();
            }
        }
Example #19
0
        public bool Setup(TcpClient tcpSocket, RTSPRequestParser parser)
        {
            string media = parser.Media;


            ServerMediaSession session = _connection.Server.lookupServerMediaSession(media);

            if (session == null)
            {
                _connection.HandleNotFound(parser);
                return(false);
            }
            // Look up information for the specified subsession (track):


            ServerMediaSubsession subsession = session.LookupSubSession(media);


            Socket socket = null;

            if (String.Compare(parser.TransportType, "RTP/AVP/TCP") == 0)
            {
                socket       = tcpSocket.Client;
                IsRTPOverTCP = true;
            }

            if ((subsession.IsMulticast && parser.TransportMode == "UNICAST") || (!subsession.IsMulticast && parser.TransportMode == "MULTICAST"))
            {
                _connection.HandleUnsupportedTransport(parser);
                return(false);
            }

            int clientRTPPort  = parser.ClientPort1;
            int clientRTCPPort = parser.ClientPort2;

            int    serverRTPPort;
            int    serverRTCPPort;
            string multiCastAddress;
            var    clientAddress = tcpSocket.Client.RemoteEndPoint as IPEndPoint;

            subsession.GetStreamParameters(out serverRTPPort, out serverRTCPPort, out multiCastAddress);

            SetupDestinations(socket, clientAddress, null, clientRTPPort, clientRTCPPort, (byte)parser.Channel1, (byte)parser.Channel2);

            StringBuilder sb = new StringBuilder();

            sb.Append("RTSP/1.0 200 OK\r\n");
            sb.AppendFormat("Server: {0}\r\n", RTSPServer.ServerVersion);
            sb.AppendFormat("Cseq: {0}\r\n", parser.Headers["CSEQ"]);

            var localIP = SocketExtensions.GetLocalIPV4Address();

            if (parser.TransportMode == "UNICAST")
            {
                sb.AppendFormat("Session: {0}\r\n", SessionId);
                sb.Append("Last-Modified: Tue, 30 Aug 2016 01:33:17 GMT\r\n");
                sb.Append("Cache-Control: must-revalidate\r\n");
                sb.Append("Date: Sat, 22 Dec 2018 16:18:03 GMT\r\n");
                sb.Append("Expires: Sun, 23 Dec 2018 12:01:28 GMT\r\n");

                if (socket == null)
                {
                    // UDP
                    sb.AppendFormat("Transport: RTP/AVP;unicast;destination={0};source={1};client_port={2}-{3};server_port={4}-{5};\r\n\r\n",
                                    clientAddress.Address,
                                    localIP,
                                    parser.ClientPort1,
                                    parser.ClientPort2,
                                    serverRTPPort,
                                    serverRTCPPort);
                }
                else
                {
                    // TCP
                    sb.AppendFormat("Transport: RTP/AVP/TCP;unicast;destination={0};source={1};interleaved={2}-{3}\r\n\r\n",
                                    clientAddress.Address,
                                    localIP,
                                    parser.Channel1,
                                    parser.Channel2);
                }
            }
            // Multicast
            else
            {
                sb.Append("Date: Sat, 22 Dec 2018 16:18:03 GMT\r\n");
                sb.AppendFormat("Transport: RTP/AVP;multicast;destination={0};source={1};port={2}-{3};ttl=255\r\n",
                                multiCastAddress,
                                localIP,
                                serverRTPPort,
                                serverRTCPPort).
                AppendFormat("Session: {0};timeout=65\r\n\r\n", SessionId);
            }

            var reply = sb.ToString();

            _connection.SendResponse(reply);
            return(true);
        }
Example #20
0
        public virtual int CompleteFrom(System.Net.Sockets.Socket socket, MemorySegment buffer)
        {
            if (IsReadOnly)
            {
                throw new InvalidOperationException("Cannot modify a RtpPacket when IsReadOnly is false.");
            }

            //If the packet is complete then return
            if (IsDisposed || IsComplete)
            {
                return(0);
            }

            // Cache the size of the original payload
            int payloadCount     = Payload.Count,
                octetsRemaining  = payloadCount,                                    //Cache how many octets remain in the payload
                offset           = Payload.Offset,                                  //Cache the offset in parsing
                sourceListOctets = ContributingSourceListOctets,                    //Cache the amount of octets required in the ContributingSourceList.
                extensionSize    = Header.Extension ? RtpExtension.MinimumSize : 0, //Cache the amount of octets required to read the ExtensionHeader
                recieved         = 0;

            //If the ContributingSourceList is not complete
            if (payloadCount < sourceListOctets)
            {
                //Calulcate the amount of octets to receive, ABS is weird and not required since paycount is checked to be less
                octetsRemaining = sourceListOctets - payloadCount; //Binary.Abs(payloadCount - sourceListOctets);

                //octetsRemaining = Binary.Min(payloadCount, sourceListOctets);

                //Allocte the memory for the required data
                if (m_OwnedOctets == null)
                {
                    m_OwnedOctets = new byte[octetsRemaining];
                }
                else
                {
                    m_OwnedOctets = m_OwnedOctets.Concat(new byte[octetsRemaining]).ToArray();
                }

                System.Net.Sockets.SocketError error;

                //Read from the stream, decrementing from octetsRemaining what was read.
                while (octetsRemaining > 0)
                {
                    //Receive octetsRemaining or less
                    int justReceived = SocketExtensions.AlignedReceive(m_OwnedOctets, offset, octetsRemaining, socket, out error);

                    //Move the offset
                    offset += justReceived;

                    //Decrement how many octets were receieved
                    octetsRemaining -= justReceived;

                    recieved += justReceived;
                }
            }

            //At the end of the sourceList
            offset = sourceListOctets;

            //ContribuingSourceList is now Complete

            //If there is a RtpExtension indicated by the RtpHeader
            if (Header.Extension)
            {
                //Determine if the extension header was read
                octetsRemaining = RtpExtension.MinimumSize - (payloadCount - offset);

                //If the extension header is not yet read
                if (octetsRemaining > 0)
                {
                    //Allocte the memory for the extension header
                    if (m_OwnedOctets == null)
                    {
                        m_OwnedOctets = new byte[octetsRemaining];
                    }
                    else
                    {
                        m_OwnedOctets = m_OwnedOctets.Concat(new byte[octetsRemaining]).ToArray();
                    }

                    System.Net.Sockets.SocketError error;

                    //Read from the socket, decrementing from octetsRemaining what was read.
                    while (octetsRemaining > 0)
                    {
                        //Receive octetsRemaining or less
                        int justReceived = SocketExtensions.AlignedReceive(m_OwnedOctets, offset, octetsRemaining, socket, out error);

                        //Move the offset
                        offset += justReceived;

                        //Decrement how many octets were receieved
                        octetsRemaining -= justReceived;

                        recieved += justReceived;
                    }
                }

                //at least 4 octets are now present in Payload @ Payload.Offset

                //Use a RtpExtension instance to read the Extension Header and data.
                using (RtpExtension extension = GetExtension())
                {
                    if (extension != null && false == extension.IsComplete)
                    {
                        //Cache the size of the RtpExtension (not including the Flags and LengthInWords [The Extension Header])
                        extensionSize = extension.Size - RtpExtension.MinimumSize;

                        //The amount of octets required for for completion are indicated by the Size property of the RtpExtension.
                        //Calulcate the amount of octets to receive
                        octetsRemaining = (payloadCount - offset) - RtpExtension.MinimumSize;

                        if (octetsRemaining > 0 && octetsRemaining < extensionSize)
                        {
                            //Allocte the memory for the required data
                            if (m_OwnedOctets == null)
                            {
                                m_OwnedOctets = new byte[octetsRemaining];
                            }
                            else
                            {
                                m_OwnedOctets = m_OwnedOctets.Concat(new byte[octetsRemaining]).ToArray();
                            }

                            System.Net.Sockets.SocketError error;

                            //Read from the stream, decrementing from octetsRemaining what was read.
                            while (octetsRemaining > 0)
                            {
                                //Receive octetsRemaining or less
                                int justReceived = SocketExtensions.AlignedReceive(m_OwnedOctets, offset, octetsRemaining, socket, out error);

                                //Move the offset
                                offset += justReceived;

                                //Decrement how many octets were receieved
                                octetsRemaining -= justReceived;

                                recieved += justReceived;
                            }
                        }
                    }
                }
            }

            //RtpExtension is now Complete

            //If the header indicates the payload has padding
            if (Header.Padding)
            {
                //Double check this math
                octetsRemaining = PaddingOctets - payloadCount;

                if (octetsRemaining > 0)
                {
                    //Allocte the memory for the required data
                    if (m_OwnedOctets == null)
                    {
                        m_OwnedOctets = new byte[octetsRemaining];
                    }
                    else
                    {
                        m_OwnedOctets = m_OwnedOctets.Concat(new byte[octetsRemaining]).ToArray();
                    }

                    offset = payloadCount;

                    //If the amount of bytes read in the padding is NOT equal to the last byte in the segment the RtpPacket is NOT complete
                    while (octetsRemaining > 0)
                    {
                        System.Net.Sockets.SocketError error;

                        //Receive 1 byte
                        //Receive octetsRemaining or less
                        int justReceived = SocketExtensions.AlignedReceive(m_OwnedOctets, offset, octetsRemaining, socket, out error);

                        //Move the offset
                        offset += justReceived;

                        recieved += justReceived;

                        octetsRemaining -= justReceived;
                    }
                }
            }

            //Padding is now complete

            //Re allocate the payload segment to include any completed data
            Payload = new MemorySegment(m_OwnedOctets, Payload.Offset, m_OwnedOctets.Length);

            //RtpPacket is complete

            return(recieved);
        }
        /// <summary>
        /// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <param name="registry">The user registry.</param>
        /// <returns></returns>
        public static async Task <ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (udpSocket == null)
            {
                throw new ArgumentNullException("udpSocket");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            if (registry == null)
            {
                throw new ArgumentNullException("registry");
            }

            var requestCode = request.TypeCode();

            if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
            }

            var bytes = request.ToBytes();

#if CF
            int bufSize = 8192;
#else
            var bufSize = udpSocket.ReceiveBufferSize;
#endif
            var reply = new byte[bufSize];

            // Whatever you change, try to keep the Send and the Receive close to each other.
            udpSocket.SendTo(bytes, receiver);

            int count;

            // IMPORTANT: follow http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx
            var args = new SocketAsyncEventArgs();
            try
            {
                args.SetBuffer(reply, 0, bufSize);
                var awaitable = new SocketAwaitable(args);
                count = await SocketExtensions.ReceiveAsync(udpSocket, awaitable);
            }
            catch (SocketException ex)
            {
                // FIXME: If you use a Mono build without the fix for this issue (https://bugzilla.novell.com/show_bug.cgi?id=599488), please uncomment this code.

                /*
                 * if (SnmpMessageExtension.IsRunningOnMono && ex.ErrorCode == 10035)
                 * {
                 *  throw TimeoutException.Create(receiver.Address, timeout);
                 * }
                 * // */

                if (ex.SocketErrorCode == SocketError.TimedOut)
                {
                    throw TimeoutException.Create(receiver.Address, 0);
                }

                throw;
            }
            finally
            {
                args.Dispose();
            }

            // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
            var response     = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
            var responseCode = response.TypeCode();
            if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
            {
                var requestId  = request.MessageId();
                var responseId = response.MessageId();
                if (responseId != requestId)
                {
                    throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
                }

                return(response);
            }

            throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
        }
        //Todo, cleanup and allow existing Rtp and Rtcp socket.

        /// <summary>
        /// Will create a <see cref="RtpClient"/> based on the given parameters
        /// </summary>
        /// <param name="sessionDescription"></param>
        /// <param name="sharedMemory"></param>
        /// <param name="incomingEvents"></param>
        /// <param name="rtcpEnabled"></param>
        /// <returns></returns>
        public static RtpClient FromSessionDescription(Sdp.SessionDescription sessionDescription, Common.MemorySegment sharedMemory = null, bool incomingEvents = true, bool rtcpEnabled = true, System.Net.Sockets.Socket existingSocket = null, int?rtpPort = null, int?rtcpPort = null, int remoteSsrc = 0, int minimumSequentialRtpPackets = 2, bool connect = true, System.Action <System.Net.Sockets.Socket> configure = null)
        {
            if (Common.IDisposedExtensions.IsNullOrDisposed(sessionDescription))
            {
                throw new System.ArgumentNullException("sessionDescription");
            }

            Sdp.Lines.SessionConnectionLine connectionLine = new Sdp.Lines.SessionConnectionLine(sessionDescription.ConnectionLine);

            System.Net.IPAddress remoteIp = System.Net.IPAddress.Parse(connectionLine.Host), localIp;

            System.Net.NetworkInformation.NetworkInterface localInterface;

            //If the socket is NOT null and IS BOUND use the localIp of the same address family
            if (object.ReferenceEquals(existingSocket, null).Equals(false) && existingSocket.IsBound)
            {
                //If the socket is IP based
                if (existingSocket.LocalEndPoint is System.Net.IPEndPoint)
                {
                    //Take the localIp from the LocalEndPoint
                    localIp = (existingSocket.LocalEndPoint as System.Net.IPEndPoint).Address;
                }
                else
                {
                    throw new System.NotSupportedException("Please create an issue for your use case.");
                }
            }
            else // There is no socket existing.
            {
                //If the remote address is the broadcast address or the remote address is multicast
                if (System.Net.IPAddress.Broadcast.Equals(remoteIp) || IPAddressExtensions.IsMulticast(remoteIp))
                {
                    //This interface should be the interface you plan on using for the Rtp communication
                    localIp = SocketExtensions.GetFirstMulticastIPAddress(remoteIp.AddressFamily, out localInterface);
                }
                else
                {
                    //This interface should be the interface you plan on using for the Rtp communication
                    localIp = SocketExtensions.GetFirstUnicastIPAddress(remoteIp.AddressFamily, out localInterface);
                }
            }

            RtpClient client = new RtpClient(sharedMemory, incomingEvents);

            byte lastChannel = 0;

            //Todo, check for session level ssrc
            //if (remoteSsrc.Equals(0))
            //{
            //    //Sdp.SessionDescriptionLine ssrcLine = sessionDescription.SsrcGroupLine; // SsrcLine @ the session level could imply Group
            //}

            //For each MediaDescription in the SessionDescription
            foreach (Media.Sdp.MediaDescription md in sessionDescription.MediaDescriptions)
            {
                //Make a RtpClient.TransportContext from the MediaDescription being parsed.
                TransportContext tc = TransportContext.FromMediaDescription(sessionDescription, lastChannel++, lastChannel++, md,
                                                                            rtcpEnabled, remoteSsrc, minimumSequentialRtpPackets,
                                                                            localIp, remoteIp, //The localIp and remoteIp
                                                                            rtpPort, rtcpPort, //The remote ports to receive data from
                                                                            connect, existingSocket, configure);

                //Try to add the context
                try
                {
                    client.AddContext(tc);
                }
                catch (System.Exception ex)
                {
                    TaggedExceptionExtensions.RaiseTaggedException(tc, "See Tag, Could not add the created TransportContext.", ex);
                }
            }

            //Return the participant
            return(client);
        }
Example #23
0
        private static void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backw      = sender as BackgroundWorker;
            ClientData       tempclient = e.Argument as ClientData;

            byte[] recvImag;
            int    senderBuffer;
            string isEnd_orPassImage;

            while (true)
            {
                NetworkStream ns = tempclient.Tcpclient.GetStream();
                StreamReader  sr = new StreamReader(ns);
                StreamWriter  sw = new StreamWriter(ns);


                try
                {
                    isEnd_orPassImage = sr.ReadLine();
                    if (isEnd_orPassImage == "end" || isEnd_orPassImage == null)
                    {
                        //string disconMessage = sr.ReadLine();
                        //Console.WriteLine(disconMessage);
                        Console.WriteLine("A Client is disconnected");
                        break;
                    }
                    senderBuffer = int.Parse(isEnd_orPassImage);

                    if (ns.CanRead)
                    {
                        Console.WriteLine("size: " + senderBuffer.ToString());
                        recvImag = new byte[senderBuffer];


                        int count = senderBuffer;
                        int read, offset = 0;

                        while (count > 0 && ((read = ns.Read(recvImag, offset, count))) > 0)
                        {
                            offset += read;
                            count  -= read;
                        }
                        if (count != 0)
                        {
                            throw new EndOfStreamException();
                        }


                        Console.WriteLine("client sent a photo (size :" + recvImag.Length.ToString() + " )");

                        ns.Flush();

                        for (int i = 0; i < numberOfClient; i++)
                        {
                            if (clientSockets[i] != tempclient)
                            {
                                ns = clientSockets[i].Tcpclient.GetStream();
                                sw = new StreamWriter(ns);
                                sr = new StreamReader(ns);
                                sw.WriteLine(senderBuffer.ToString());
                                sw.Flush();
                                ns.Write(recvImag, 0, recvImag.Length); //送回去
                                ns.Flush();
                            }
                        }
                        Console.WriteLine("you send it back");
                        Thread.Sleep(1000);
                    }
                }
                catch
                {
                    if (SocketExtensions.IsConnected(tempclient.Socket) == false)
                    {
                        string dicString = "Client " + tempclient.Name + " is disconnected ( " + tempclient.Ip + " )";

                        byte[] sendB = Encoding.UTF8.GetBytes(dicString);
                        udpClientSocket.Send(sendB, sendB.Length, ipGp);
                        clientDisconnet = true;
                        Console.WriteLine("broadcast : " + dicString);

                        clientSockets.Remove(tempclient);
                        if (clientSockets.Count == 0)
                        {
                            Console.WriteLine("No Client is Online Now.....");
                        }
                    }
                }
            }
        }
Example #24
0
 public void Configure(ServerConfig config)
 {
     _socket = SocketExtensions.Create(config)
               .Bind(config);
 }