コード例 #1
0
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public void Dispose()
        {
            if (m_IsDisposed)
            {
                return;
            }
            try{
                if (m_IsRunning)
                {
                    Stop();
                }
            }
            catch {
            }
            m_IsDisposed = true;

            // Release events.
            this.Error            = null;
            this.SessionCompleted = null;

            m_pQueues     = null;
            m_pSmartHosts = null;

            m_pDsnClient.Dispose();
            m_pDsnClient = null;
        }
コード例 #2
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="stack">Owner SIP stack.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stack</b> is null reference.</exception>
        internal SIP_TransportLayer(SIP_Stack stack)
        {
            if(stack == null){
                throw new ArgumentNullException("stack");
            }

            m_pStack = stack;

            m_pUdpServer = new UDP_Server();
            m_pUdpServer.ProcessMode = UDP_ProcessMode.Parallel;
            m_pUdpServer.PacketReceived += new PacketReceivedHandler(m_pUdpServer_PacketReceived);
            m_pUdpServer.Error += new ErrorEventHandler(m_pUdpServer_Error);

            m_pTcpServer = new TCP_Server<TCP_ServerSession>();
            m_pTcpServer.SessionCreated += new EventHandler<TCP_ServerSessionEventArgs<TCP_ServerSession>>(m_pTcpServer_SessionCreated);

            m_pFlowManager = new SIP_FlowManager(this);

            m_pBinds = new IPBindInfo[]{};

            m_pRandom = new Random();

            m_pLocalIPv4 = new CircleCollection<IPAddress>();
            m_pLocalIPv6 = new CircleCollection<IPAddress>();
        }
コード例 #3
0
        /// <summary>
        /// Starts SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Start()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_pLocalEndPointIPv4 = new CircleCollection <IPBindInfo>();
            m_pLocalEndPointIPv6 = new CircleCollection <IPBindInfo>();
            m_pSessions          = new TCP_SessionCollection <Relay_Session>();
            m_pConnectionsPerIP  = new Dictionary <IPAddress, long>();

            Thread tr1 = new Thread(new ThreadStart(this.Run));

            tr1.Start();

            m_pTimerTimeout          = new TimerEx(30000);
            m_pTimerTimeout.Elapsed += new System.Timers.ElapsedEventHandler(m_pTimerTimeout_Elapsed);
            m_pTimerTimeout.Start();
        }
コード例 #4
0
ファイル: UDP_Server.cs プロジェクト: andreikalatsei/milskype
        /// <summary>
        /// Processes incoming UDP data and queues it for processing.
        /// </summary>
        private void ProcessIncomingUdp()
        {
            // Create Round-Robin for listening points.
            CircleCollection <Socket> listeningEPs = new CircleCollection <Socket>();

            foreach (Socket socket in m_pSockets)
            {
                listeningEPs.Add(socket);
            }

            byte[] buffer = new byte[m_MTU];
            while (m_IsRunning)
            {
                try{
                    // Maximum allowed UDP queued packts exceeded.
                    if (m_pQueuedPackets.Count >= m_MaxQueueSize)
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        // Roun-Robin sockets.
                        bool receivedData = false;
                        for (int i = 0; i < listeningEPs.Count; i++)
                        {
                            Socket socket = listeningEPs.Next();
                            // Read data only when there is some, otherwise we block thread.
                            if (socket.Poll(0, SelectMode.SelectRead))
                            {
                                // Receive data.
                                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                                int      received = socket.ReceiveFrom(buffer, ref remoteEP);
                                m_BytesReceived += received;
                                m_PacketsReceived++;

                                // Queue received packet.
                                byte[] data = new byte[received];
                                Array.Copy(buffer, data, received);
                                lock (m_pQueuedPackets){
                                    m_pQueuedPackets.Enqueue(new UdpPacket(socket, (IPEndPoint)remoteEP, data));
                                }

                                // We received data, so exit round-robin loop.
                                receivedData = true;
                                break;
                            }
                        }
                        // We didn't get any data from any listening point, we must sleep or we use 100% CPU.
                        if (!receivedData)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
                catch (Exception x) {
                    OnError(x);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Stops UDP server.
        /// </summary>
        public void Stop()
        {
            if (!m_IsRunning)
            {
                return;
            }
            m_IsRunning = false;

            m_pQueuedPackets = null;
            // Close sockets.
            foreach (Socket socket in m_pSockets)
            {
                socket.Close();
            }
            m_pSockets         = null;
            m_pSendSocketsIPv4 = null;
            m_pSendSocketsIPv6 = null;
        }
コード例 #6
0
        /// <summary>
        /// Stops SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Stop()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (!m_IsRunning)
            {
                return;
            }
            m_IsRunning = false;

            // TODO: We need to send notify to all not processed messages, then they can be Disposed as needed.

            // Clean up.
            m_pLocalEndPoints = null;
            //m_pSessions.Dispose();
            m_pSessions         = null;
            m_pConnectionsPerIP = null;
        }
コード例 #7
0
        /// <summary>
        /// Stops UDP server.
        /// </summary>
        public void Stop()
        {
            if (!m_IsRunning)
            {
                return;
            }
            m_IsRunning = false;

            foreach (UDP_DataReceiver receiver in m_pDataReceivers)
            {
                receiver.Dispose();
            }
            m_pDataReceivers = null;
            foreach (Socket socket in m_pSockets)
            {
                socket.Close();
            }
            m_pSockets         = null;
            m_pSendSocketsIPv4 = null;
            m_pSendSocketsIPv6 = null;
        }
コード例 #8
0
        /// <summary>
        /// Starts SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Start()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_pLocalEndPoints   = new CircleCollection <IPBindInfo>();
            m_pSessions         = new TCP_SessionCollection <Relay_Session>();
            m_pConnectionsPerIP = new Dictionary <IPAddress, long>();

            Thread tr1 = new Thread(Run);

            tr1.Start();

            Thread tr2 = new Thread(Run_CheckTimedOutSessions);

            tr2.Start();
        }
コード例 #9
0
ファイル: Relay_Server.cs プロジェクト: dioptre/nkd
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public void Dispose()
        {
            if(m_IsDisposed){
                return;
            }
            try{
                if(m_IsRunning){
                    Stop();
                }
            }
            catch{
            }
            m_IsDisposed = true;

            // Release events.
            this.Error = null;
            this.SessionCompleted = null;

            m_pQueues     = null;
            m_pSmartHosts = null;

            m_pDsnClient.Dispose();
            m_pDsnClient = null;
        }
コード例 #10
0
ファイル: Relay_Server.cs プロジェクト: dioptre/nkd
 /// <summary>
 /// Default constructor.
 /// </summary>
 public Relay_Server()
 {
     m_pQueues     = new List<Relay_Queue>();
     m_pSmartHosts = new CircleCollection<Relay_SmartHost>();
     m_pDsnClient  = new Dns_Client();
 }
コード例 #11
0
ファイル: Relay_Server.cs プロジェクト: dioptre/nkd
        /// <summary>
        /// Stops SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Stop()
        {
            if(m_IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(!m_IsRunning){
                return;
            }
            m_IsRunning = false;

            // TODO: We need to send notify to all not processed messages, then they can be Disposed as needed.
                        
            // Clean up.            
            m_pLocalEndPointIPv4 = null;
            m_pLocalEndPointIPv6 = null;
            //m_pSessions.Dispose();
            m_pSessions = null;
            m_pConnectionsPerIP = null;
            m_pTimerTimeout.Dispose();
            m_pTimerTimeout = null;
        }
コード例 #12
0
ファイル: Relay_Server.cs プロジェクト: dioptre/nkd
        /// <summary>
        /// Starts SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Start()
        {
            if(m_IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(m_IsRunning){
                return;
            }
            m_IsRunning = true;

            m_pLocalEndPointIPv4 = new CircleCollection<IPBindInfo>();
            m_pLocalEndPointIPv6 = new CircleCollection<IPBindInfo>();
            m_pSessions          = new TCP_SessionCollection<Relay_Session>();
            m_pConnectionsPerIP  = new Dictionary<IPAddress,long>();

            Thread tr1 = new Thread(new ThreadStart(this.Run));
            tr1.Start();

            m_pTimerTimeout = new TimerEx(30000);
            m_pTimerTimeout.Elapsed += new System.Timers.ElapsedEventHandler(m_pTimerTimeout_Elapsed);
            m_pTimerTimeout.Start();
        }
コード例 #13
0
        /// <summary>
        /// Stops UDP server.
        /// </summary>
        public void Stop()
        {
            if (!m_IsRunning)
            {
                return;
            }
            m_IsRunning = false;

            m_pQueuedPackets = null;
            // Close sockets.
            foreach (Socket socket in m_pSockets)
            {
                socket.Close();
            }
            m_pSockets = null;
            m_pSendSocketsIPv4 = null;
            m_pSendSocketsIPv6 = null;
        }
コード例 #14
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="cname">Canonical name of participant.</param>
 /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception>
 public RTP_Participant_Local(string cname) : base(cname)
 {
     m_pOtionalItemsRoundRobin = new CircleCollection<string>();
 }
コード例 #15
0
ファイル: AudioIn.cs プロジェクト: dioptre/nkd
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="device">Input device.</param>
            /// <param name="samplesPerSec">Sample rate, in samples per second (hertz). For PCM common values are 
            /// 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz.</param>
            /// <param name="bitsPerSample">Bits per sample. For PCM 8 or 16 are the only valid values.</param>
            /// <param name="channels">Number of channels.</param>
            /// <param name="bufferSize">Specifies recording buffer size.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>outputDevice</b> is null.</exception>
            /// <exception cref="ArgumentException">Is raised when any of the aruments has invalid value.</exception>
            public WaveIn(AudioInDevice device,int samplesPerSec,int bitsPerSample,int channels,int bufferSize)
            {
                if(device == null){
                    throw new ArgumentNullException("device");
                }
                if(samplesPerSec < 8000){
                    throw new ArgumentException("Argument 'samplesPerSec' value must be >= 8000.");
                }
                if(bitsPerSample < 8){
                    throw new ArgumentException("Argument 'bitsPerSample' value must be >= 8.");
                }
                if(channels < 1){
                    throw new ArgumentException("Argument 'channels' value must be >= 1.");
                }

                m_pInDevice     = device;
                m_SamplesPerSec = samplesPerSec;
                m_BitsPerSample = bitsPerSample;
                m_Channels      = channels;
                m_BufferSize    = bufferSize;
                m_BlockSize     = m_Channels * (m_BitsPerSample / 8);
                m_pBuffers      = new CircleCollection<BufferItem>();
                m_pReadBuffer   = new FifoBuffer(32000);

                // Try to open wav device.            
                WAVEFORMATEX format = new WAVEFORMATEX();
                format.wFormatTag      = WavFormat.PCM;
                format.nChannels       = (ushort)m_Channels;
                format.nSamplesPerSec  = (uint)samplesPerSec;                        
                format.nAvgBytesPerSec = (uint)(m_SamplesPerSec * m_Channels * (m_BitsPerSample / 8));
                format.nBlockAlign     = (ushort)m_BlockSize;
                format.wBitsPerSample  = (ushort)m_BitsPerSample;
                format.cbSize          = 0; 
                // We must delegate reference, otherwise GC will collect it.
                m_pWaveInProc = new waveInProc(this.OnWaveInProc);
                int result = waveInOpen(out m_pWavDevHandle,m_pInDevice.Index,format,m_pWaveInProc,0,WavConstants.CALLBACK_FUNCTION);
                if(result != MMSYSERR.NOERROR){
                    throw new Exception("Failed to open wav device, error: " + result.ToString() + ".");
                }

                CreateBuffers();
            }
コード例 #16
0
        /// <summary>
        /// Starts SMTP relay server.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        public virtual void Start()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_pLocalEndPoints = new CircleCollection<IPBindInfo>();
            m_pSessions = new TCP_SessionCollection<Relay_Session>();
            m_pConnectionsPerIP = new Dictionary<IPAddress, long>();

            Thread tr1 = new Thread(Run);
            tr1.Start();

            Thread tr2 = new Thread(Run_CheckTimedOutSessions);
            tr2.Start();
        }
コード例 #17
0
        /// <summary>
        /// Processes incoming UDP data and queues it for processing.
        /// </summary>
        private void ProcessIncomingUdp()
        {
            // Create Round-Robin for listening points.
            CircleCollection<Socket> listeningEPs = new CircleCollection<Socket>();
            foreach (Socket socket in m_pSockets)
            {
                listeningEPs.Add(socket);
            }

            byte[] buffer = new byte[m_MTU];
            while (m_IsRunning)
            {
                try
                {
                    // Maximum allowed UDP queued packts exceeded.
                    if (m_pQueuedPackets.Count >= m_MaxQueueSize)
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        // Roun-Robin sockets.
                        bool receivedData = false;
                        for (int i = 0; i < listeningEPs.Count; i++)
                        {
                            Socket socket = listeningEPs.Next();
                            // Read data only when there is some, otherwise we block thread.
                            if (socket.Poll(0, SelectMode.SelectRead))
                            {
                                // Receive data.
                                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                                int received = socket.ReceiveFrom(buffer, ref remoteEP);
                                m_BytesReceived += received;
                                m_PacketsReceived++;

                                // Queue received packet.
                                byte[] data = new byte[received];
                                Array.Copy(buffer, data, received);
                                lock (m_pQueuedPackets)
                                {
                                    m_pQueuedPackets.Enqueue(new UdpPacket(socket, (IPEndPoint) remoteEP, data));
                                }

                                // We received data, so exit round-robin loop.
                                receivedData = true;
                                break;
                            }
                        }
                        // We didn't get any data from any listening point, we must sleep or we use 100% CPU.
                        if (!receivedData)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
                catch (Exception x)
                {
                    OnError(x);
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Starts UDP server.
        /// </summary>
        public void Start()
        {
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_StartTime      = DateTime.Now;
            m_pQueuedPackets = new Queue <UdpPacket>();

            // Run only if we have some listening point.
            if (m_pBindings != null)
            {
                // We must replace IPAddress.Any to all available IPs, otherwise it's impossible to send
                // reply back to UDP packet sender on same local EP where packet received. This is very
                // important when clients are behind NAT.
                List <IPEndPoint> listeningEPs = new List <IPEndPoint>();
                foreach (IPEndPoint ep in m_pBindings)
                {
                    if (ep.Address.Equals(IPAddress.Any))
                    {
                        // Add localhost.
                        IPEndPoint epLocalhost = new IPEndPoint(IPAddress.Loopback, ep.Port);
                        if (!listeningEPs.Contains(epLocalhost))
                        {
                            listeningEPs.Add(epLocalhost);
                        }
                        // Add all host IPs.
                        foreach (IPAddress ip in Dns.GetHostAddresses(""))
                        {
                            IPEndPoint epNew = new IPEndPoint(ip, ep.Port);
                            if (!listeningEPs.Contains(epNew))
                            {
                                listeningEPs.Add(epNew);
                            }
                        }
                    }
                    else
                    {
                        if (!listeningEPs.Contains(ep))
                        {
                            listeningEPs.Add(ep);
                        }
                    }
                }

                // Create sockets.
                m_pSockets = new List <Socket>();
                foreach (IPEndPoint ep in listeningEPs)
                {
                    try
                    {
                        m_pSockets.Add(Core.CreateSocket(ep, ProtocolType.Udp));
                    }
                    catch (Exception x)
                    {
                        OnError(x);
                    }
                }

                // Create round-robin send sockets. NOTE: We must skip localhost, it can't be used
                // for sending out of server.
                m_pSendSocketsIPv4 = new CircleCollection <Socket>();
                m_pSendSocketsIPv6 = new CircleCollection <Socket>();
                foreach (Socket socket in m_pSockets)
                {
                    if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (!((IPEndPoint)socket.LocalEndPoint).Address.Equals(IPAddress.Loopback))
                        {
                            m_pSendSocketsIPv4.Add(socket);
                        }
                    }
                    else if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        m_pSendSocketsIPv6.Add(socket);
                    }
                }

                Thread tr = new Thread(ProcessIncomingUdp);
                tr.Start();
                Thread tr2 = new Thread(ProcessQueuedPackets);
                tr2.Start();
            }
        }
コード例 #19
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public Relay_Server()
 {
     m_pQueues     = new List <Relay_Queue>();
     m_pSmartHosts = new CircleCollection <Relay_SmartHost>();
 }
コード例 #20
0
        /// <summary>
        /// Starts UDP server.
        /// </summary>
        public void Start()
        {
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_StartTime = DateTime.Now;
            m_pQueuedPackets = new Queue<UdpPacket>();

            // Run only if we have some listening point.
            if (m_pBindings != null)
            {
                // We must replace IPAddress.Any to all available IPs, otherwise it's impossible to send 
                // reply back to UDP packet sender on same local EP where packet received. This is very 
                // important when clients are behind NAT.
                List<IPEndPoint> listeningEPs = new List<IPEndPoint>();
                foreach (IPEndPoint ep in m_pBindings)
                {
                    if (ep.Address.Equals(IPAddress.Any))
                    {
                        // Add localhost.
                        IPEndPoint epLocalhost = new IPEndPoint(IPAddress.Loopback, ep.Port);
                        if (!listeningEPs.Contains(epLocalhost))
                        {
                            listeningEPs.Add(epLocalhost);
                        }
                        // Add all host IPs.
                        foreach (IPAddress ip in Dns.GetHostAddresses(""))
                        {
                            IPEndPoint epNew = new IPEndPoint(ip, ep.Port);
                            if (!listeningEPs.Contains(epNew))
                            {
                                listeningEPs.Add(epNew);
                            }
                        }
                    }
                    else
                    {
                        if (!listeningEPs.Contains(ep))
                        {
                            listeningEPs.Add(ep);
                        }
                    }
                }

                // Create sockets.
                m_pSockets = new List<Socket>();
                foreach (IPEndPoint ep in listeningEPs)
                {
                    try
                    {
                        m_pSockets.Add(Core.CreateSocket(ep, ProtocolType.Udp));
                    }
                    catch (Exception x)
                    {
                        OnError(x);
                    }
                }

                // Create round-robin send sockets. NOTE: We must skip localhost, it can't be used 
                // for sending out of server.
                m_pSendSocketsIPv4 = new CircleCollection<Socket>();
                m_pSendSocketsIPv6 = new CircleCollection<Socket>();
                foreach (Socket socket in m_pSockets)
                {
                    if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (!((IPEndPoint) socket.LocalEndPoint).Address.Equals(IPAddress.Loopback))
                        {
                            m_pSendSocketsIPv4.Add(socket);
                        }
                    }
                    else if ((socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        m_pSendSocketsIPv6.Add(socket);
                    }
                }

                Thread tr = new Thread(ProcessIncomingUdp);
                tr.Start();
                Thread tr2 = new Thread(ProcessQueuedPackets);
                tr2.Start();
            }
        }
コード例 #21
0
ファイル: UDP_Server.cs プロジェクト: dioptre/nkd
        /// <summary>
        /// Starts UDP server.
        /// </summary>
        public void Start()
        {
            if(m_IsRunning){
                return;
            }
            m_IsRunning = true;

            m_StartTime = DateTime.Now;
            m_pDataReceivers = new List<UDP_DataReceiver>();

            // Run only if we have some listening point.
            if(m_pBindings != null){
                // We must replace IPAddress.Any to all available IPs, otherwise it's impossible to send 
                // reply back to UDP packet sender on same local EP where packet received. This is very 
                // important when clients are behind NAT.
                List<IPEndPoint> listeningEPs = new List<IPEndPoint>();
                foreach(IPEndPoint ep in m_pBindings){                    
                    if(ep.Address.Equals(IPAddress.Any)){
                        // Add localhost.
                        IPEndPoint epLocalhost = new IPEndPoint(IPAddress.Loopback,ep.Port);
                        if(!listeningEPs.Contains(epLocalhost)){
                            listeningEPs.Add(epLocalhost);
                        }
                        // Add all host IPs.
                        foreach(IPAddress ip in System.Net.Dns.GetHostAddresses("")){
                            IPEndPoint epNew = new IPEndPoint(ip,ep.Port);
                            if(!listeningEPs.Contains(epNew)){
                                listeningEPs.Add(epNew);
                            }
                        }
                    }
                    else{
                        if(!listeningEPs.Contains(ep)){
                            listeningEPs.Add(ep);
                        }
                    }
                }

                // Create sockets.
                m_pSockets = new List<Socket>();
                foreach(IPEndPoint ep in listeningEPs){                    
                    try{
                        Socket socket = Net_Utils.CreateSocket(ep,ProtocolType.Udp);
                        m_pSockets.Add(socket);

                        // Create UDP data receivers.
                        for(int i=0;i<m_ReceiversPerSocket;i++){
                            UDP_DataReceiver receiver = new UDP_DataReceiver(socket);
                            receiver.PacketReceived += delegate(object s,UDP_e_PacketReceived e){
                                try{
                                    ProcessUdpPacket(e);
                                }
                                catch(Exception x){
                                    OnError(x);
                                }
                            };
                            receiver.Error += delegate(object s,ExceptionEventArgs e){
                                OnError(e.Exception);
                            };
                            m_pDataReceivers.Add(receiver);
                            receiver.Start();
                        }
                    }
                    catch(Exception x){
                        OnError(x);
                    }
                }
           
                // Create round-robin send sockets. NOTE: We must skip localhost, it can't be used 
                // for sending out of server.
                m_pSendSocketsIPv4 = new CircleCollection<Socket>();
                m_pSendSocketsIPv6 = new CircleCollection<Socket>();
                foreach(Socket socket in m_pSockets){
                    if(((IPEndPoint)socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetwork){
                        if(!((IPEndPoint)socket.LocalEndPoint).Address.Equals(IPAddress.Loopback)){                            
                            m_pSendSocketsIPv4.Add(socket);
                        }
                    }
                    else if(((IPEndPoint)socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetworkV6){
                        m_pSendSocketsIPv6.Add(socket);
                    }                    
                }
            }
        }
コード例 #22
0
ファイル: UDP_Server.cs プロジェクト: dioptre/nkd
        /// <summary>
        /// Stops UDP server.
        /// </summary>
        public void Stop()
        {
            if(!m_IsRunning){
                return;
            }
            m_IsRunning = false;

            foreach(UDP_DataReceiver receiver in m_pDataReceivers){
                receiver.Dispose();
            }
            m_pDataReceivers = null; 
            foreach(Socket socket in m_pSockets){
                socket.Close();
            }
            m_pSockets = null;
            m_pSendSocketsIPv4 = null;
            m_pSendSocketsIPv6 = null;
        }
コード例 #23
0
ファイル: SocketServer.cs プロジェクト: iraychen/ourmsg
		/// <summary>
		/// Starts proccessiong incoming connections (Accepts and queues connections).
		/// </summary>
		private void StartProcCons()
		{	
			try{
                CircleCollection<IPBindInfo> binds = new CircleCollection<IPBindInfo>();
                foreach(IPBindInfo bindInfo in m_pBindInfo){
                    Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
				    s.Bind(new IPEndPoint(bindInfo.IP,bindInfo.Port));
				    s.Listen(500);
                
                    bindInfo.Tag = s;
                    binds.Add(bindInfo);
                }

                // Accept connections and queue them			
				while(m_Running){
					// We have reached maximum connection limit
					if(m_pSessions.Count > m_MaxConnections){
						// Wait while some active connectins are closed
						while(m_pSessions.Count > m_MaxConnections){
							Thread.Sleep(100);
						}
					}

                    // Get incomong connection
                    IPBindInfo bindInfo = binds.Next();

                    // There is waiting connection
                    if(m_Running && ((Socket)bindInfo.Tag).Poll(0,SelectMode.SelectRead)){
                        // Accept incoming connection
					    Socket s = ((Socket)bindInfo.Tag).Accept();
                                                
        				// Add session to queue
		        		lock(m_pQueuedConnections){
				        	m_pQueuedConnections.Enqueue(new QueuedConnection(s,bindInfo));
					    }
                    }
					
                    Thread.Sleep(2);
				}
			}
			catch(SocketException x){
				// Socket listening stopped, happens when StopServer is called.
				// We need just skip this error.
				if(x.ErrorCode == 10004){			
				}
				else{
					OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:",x);
				}
			}
			catch(Exception x){
				OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:",x);
			}
		}
コード例 #24
0
        /// <summary>
        /// Starts UDP server.
        /// </summary>
        public void Start()
        {
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            m_StartTime      = DateTime.Now;
            m_pDataReceivers = new List <UDP_DataReceiver>();

            // Run only if we have some listening point.
            if (m_pBindings != null)
            {
                // We must replace IPAddress.Any to all available IPs, otherwise it's impossible to send
                // reply back to UDP packet sender on same local EP where packet received. This is very
                // important when clients are behind NAT.
                List <IPEndPoint> listeningEPs = new List <IPEndPoint>();
                foreach (IPEndPoint ep in m_pBindings)
                {
                    if (ep.Address.Equals(IPAddress.Any))
                    {
                        // Add localhost.
                        IPEndPoint epLocalhost = new IPEndPoint(IPAddress.Loopback, ep.Port);
                        if (!listeningEPs.Contains(epLocalhost))
                        {
                            listeningEPs.Add(epLocalhost);
                        }
                        // Add all host IPs.
                        foreach (IPAddress ip in System.Net.Dns.GetHostAddresses(""))
                        {
                            IPEndPoint epNew = new IPEndPoint(ip, ep.Port);
                            if (!listeningEPs.Contains(epNew))
                            {
                                listeningEPs.Add(epNew);
                            }
                        }
                    }
                    else
                    {
                        if (!listeningEPs.Contains(ep))
                        {
                            listeningEPs.Add(ep);
                        }
                    }
                }

                uint IOC_IN            = 0x80000000;
                uint IOC_VENDOR        = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                // Create sockets.
                m_pSockets = new List <Socket>();
                foreach (IPEndPoint ep in listeningEPs)
                {
                    try{
                        Socket socket = Net_Utils.CreateSocket(ep, ProtocolType.Udp);

                        // To avoid : "An existing connection was forcibly closed by the remote host"

                        socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

                        m_pSockets.Add(socket);

                        // Create UDP data receivers.
                        for (int i = 0; i < m_ReceiversPerSocket; i++)
                        {
                            UDP_DataReceiver receiver = new UDP_DataReceiver(socket);
                            receiver.PacketReceived += delegate(object s, UDP_e_PacketReceived e){
                                try{
                                    ProcessUdpPacket(e);
                                }
                                catch (Exception x) {
                                    OnError(x);
                                }
                            };
                            receiver.Error += delegate(object s, ExceptionEventArgs e){
                                OnError(e.Exception);
                            };
                            m_pDataReceivers.Add(receiver);
                            receiver.Start();
                        }
                    }
                    catch (Exception x) {
                        OnError(x);
                    }
                }

                // Create round-robin send sockets. NOTE: We must skip localhost, it can't be used
                // for sending out of server.
                m_pSendSocketsIPv4 = new CircleCollection <Socket>();
                m_pSendSocketsIPv6 = new CircleCollection <Socket>();
                foreach (Socket socket in m_pSockets)
                {
                    if (((IPEndPoint)socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (!((IPEndPoint)socket.LocalEndPoint).Address.Equals(IPAddress.Loopback))
                        {
                            m_pSendSocketsIPv4.Add(socket);
                        }
                    }
                    else if (((IPEndPoint)socket.LocalEndPoint).AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        m_pSendSocketsIPv6.Add(socket);
                    }
                }
            }
        }
コード例 #25
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="cname">Canonical name of participant.</param>
 /// <exception cref="ArgumentNullException">Is raised when <b>cname</b> is null reference.</exception>
 public RTP_Participant_Local(string cname) : base(cname)
 {
     m_pOtionalItemsRoundRobin = new CircleCollection <string>();
 }
コード例 #26
0
        /// <summary>
        /// Processes incoming SIP UDP messages or incoming new SIP connections.
        /// </summary>
        private void ProcessIncomingData()
        {
            try{
                // If no binds, wait some to be created.
                while(m_pSipStack.BindInfo.Length == 0 && m_IsRunning){
                    System.Threading.Thread.Sleep(100);
                }

                //--- Create listening sockets --------------------------------------------------------------
                foreach(BindInfo bindInfo in m_pSipStack.BindInfo){
                    // TCP
                    if(bindInfo.Protocol == BindInfoProtocol.TCP){
                        Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                        s.Bind(new IPEndPoint(bindInfo.IP,bindInfo.Port));
                        s.Listen(500);

                        m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,bindInfo.SSL,bindInfo.SSL_Certificate));
                    }
                    // UDP
                    else if(bindInfo.Protocol == BindInfoProtocol.UDP){
                        // If any IP, replicate socket for each IP, other can't get LocalEndpoint for UDP socket.
                        if(bindInfo.IP.Equals(IPAddress.Any)){
                            IPAddress[] addresses = System.Net.Dns.GetHostAddresses("");
                            foreach(IPAddress address in addresses){
                                // IPv4
                                if(address.AddressFamily == AddressFamily.InterNetwork){
                                    Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
                                    s.Bind(new IPEndPoint(address,bindInfo.Port));

                                    m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                                }
                                // IPv6
                                /*
                                else{
                                    Socket s = new Socket(AddressFamily.InterNetworkV6,SocketType.Dgram,ProtocolType.Udp);
                                    s.Bind(new IPEndPoint(address,bindInfo.Port));

                                    m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                                }*/
                            }
                        }
                        else{
                            Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
                            s.Bind(new IPEndPoint(bindInfo.IP,bindInfo.Port));

                            m_pListeningPoints.Add(new SipListeningPoint(bindInfo.Protocol,s,false,null));
                        }
                    }
                }

                CircleCollection<SipListeningPoint> binds = new CircleCollection<SipListeningPoint>();
                binds.Add(m_pListeningPoints.ToArray());
                //-------------------------------------------------------------------------------------------

                // Accept incoming connections and datagrams.
                while(m_IsRunning){
                    try{
                        // Check that maximum allowed connections not exceeded.
                        if(m_pSipStack.MaximumConnections > 0 && m_pTcpReceiviePipes.Count > m_pSipStack.MaximumConnections){
                            // Sleep here or CPU used 100%
                            Thread.Sleep(1);

                            // Step to next while loop.
                            continue;
                        }

                        // Check next listening point and queue it up when Socket has data or connection attampt.
                        SipListeningPoint listeningPoint = binds.Next();
                        if(listeningPoint.Socket.Poll(0,SelectMode.SelectRead)){
                            Socket socket = listeningPoint.Socket;

                            // TCP, TLS
                            if(listeningPoint.Protocol == BindInfoProtocol.TCP){
                                // Accept incoming connection.
                                SocketEx clientSocket = new SocketEx(socket.Accept());

                                // SSL
                                if(listeningPoint.SSL){
                                    clientSocket.SwitchToSSL(listeningPoint.Certificate);
                                }

                                // Queue for futher processing.
                                m_pTcpReceiviePipes.Add(new SipTcpPipe(this,clientSocket));
                            }
                            // UDP
                            else if(listeningPoint.Protocol == BindInfoProtocol.UDP){
                                // Receive data packet.
                                byte[] dataBuffer = new byte[32000];
                                EndPoint remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any,0);
                                int size = socket.ReceiveFrom(dataBuffer,ref remoteEndPoint);

                                // Copy received data to new buffer what is exactly received size.
                                byte[] data = new byte[size];
                                Array.Copy(dataBuffer,data,size);

                                // Queue UDP datagram for processing.
                                ThreadPool.QueueUserWorkItem(
                                    new WaitCallback(this.Process),
                                    new SIP_Packet(socket,(IPEndPoint)remoteEndPoint,data)
                                );
                            }
                        }

                        // Sleep here or CPU used 100%
                        Thread.Sleep(1);
                    }
                    catch(SocketException x){
                        // Just skip recieve errors.

                        /* WSAETIMEDOUT 10060 Connection timed out.
                            A connection attempt failed because the connected party did not properly respond
                            after a period of time, or the established connection failed because the connected
                            host has failed to respond.
                        */
                        if(x.ErrorCode == 10060){
                            // Skip
                        }
                        /* WSAECONNRESET 10054 Connection reset by peer.
                            An existing connection was forcibly closed by the remote host. This normally results
                            if the peer application on the remote host is suddenly stopped, the host is rebooted,
                           the host or remote network interface is disabled, or the remote host uses a hard close.
                        */
                        else if(x.ErrorCode == 10054){
                            // Skip
                        }
                        else{
                            m_pSipStack.OnError(x);
                        }
                    }
                    catch(Exception x){
                        m_pSipStack.OnError(x);
                    }
                }
            }
            catch(Exception x){
                m_pSipStack.OnError(x);
            }
        }