Dispose() public méthode

public Dispose ( ) : void
Résultat void
Exemple #1
0
        /// <summary>
        /// 停止服务
        /// </summary>
        public void Dispose()
        {
            if (socket != null)
            {
#if DotNetStandard
                AutoCSer.Net.TcpServer.CommandBase.CloseServer(socket);
#else
                socket.Dispose();
#endif
                socket = null;
            }
        }
Exemple #2
0
        /// <summary>
        /// Stop listening and close the current socket connection, also releases all resources.
        /// </summary>
        private void StopListeningEx()
        {
            _isListening = false;

            try
            {
                // Stop polling.
                _multiplexer.StopPolling();
            }
            catch { }

            try
            {
                // Clear last error.
                ClearLastError();

                // Shutdown the socket.
                if (_socket != null)
                {
                    _socket.Shutdown(SocketShutdown.Both);
                }
            }
            catch (Exception ex)
            {
                SetLastError(ex);
            }

            try
            {
                // Close the socket.
                if (_socket != null)
                {
                    _socket.Disconnect(false);
                }
            }
            catch { }

            try
            {
                // Close the socket.
                if (_socket != null)
                {
                    _socket.Close();
                    _socket.Dispose();
                }
            }
            catch { }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            mServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                IPAddress HostIp = IPAddress.Any;
                IPEndPoint iep = new IPEndPoint(HostIp, 2626);
                BlinkLog.I("Start Server Socket...");
                mServer.Bind(iep);
                mServer.Listen(Int32.MaxValue);
                mThread = new Thread(Run);
                mThread.Start();

            }
            catch (Exception)
            {
                BlinkLog.E("Start Server Error.");
            }

            BlinkLog.I("=========PRESS ANY KEY TO EXIT==========");
            Console.ReadKey();

            IsExit = true;

            if (mThread != null)
            {
                mThread.Interrupt();
            }
            mServer.Dispose();
            mServer.Close();
        }
        public static int DestorySocket(Socket socket)
        {
            int r = -1;
            try
            {
                //if (_socket.Connected)
                //{
                //    _socket.Disconnect(false);

                //}
                if (socket != null)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.DisconnectAsync(null);
                    
                    socket.Close();
                    socket.Dispose();
                    socket = null;
                }
                r = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                r = -1;
            }
            return r;
        }
Exemple #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Witaj w programie wypisujacym informacje o polaczeniu z witryna\n");
            Console.WriteLine("Podaj adres witryny: \n");
            string adresStrony = Console.ReadLine();
            Console.WriteLine("\n");
            var adresy = Dns.GetHostAddresses(adresStrony);
            var port = 80;
            foreach (var adresIp in adresy)
            {
                var gniazdo = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    gniazdo.Connect(adresIp, port);
                    Console.WriteLine("Strona: " + adresStrony);
                    Console.WriteLine("IP serwera: " + ((IPEndPoint)gniazdo.RemoteEndPoint).Address.ToString());
                    Console.WriteLine("Numer portu zdalnego połączenia: " + ((IPEndPoint)gniazdo.RemoteEndPoint).Port.ToString());
                    Console.WriteLine("Numer portu lokalnego z którego dokonywane jest połączenie " + ((IPEndPoint)gniazdo.LocalEndPoint).Port.ToString());
                }
                catch (SocketException)
                {
                    Console.WriteLine("błąd połączenia z portem");
                }
                finally
                {
                    gniazdo.Dispose();
                }
            }

            Console.ReadKey();
        }
 public PSTUClient()
 {
     IPAddress ipAddr = IPAddress.Parse(Properties.Settings.Default.IP);
     _endPoint = new IPEndPoint(ipAddr, 11000);
     _client = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         _client.Connect(_endPoint);
         byte[] data = new byte[(1024 * 1024) *5 ];
         int length = _client.Receive(data);
         if (length > 0)
         {
             Array.Resize(ref data, length);
             var path = "students.xml";
             IO.CreateFile(data, path);
             Students = File.ReadLines(path).ToArray();
             IO.DeleteFile(path);
         }
         Recieve();
     }
     catch
     {
         _client.Dispose();
         throw;
     }
 }
Exemple #7
0
        private async ValueTask DisposeSocketAsync()
        {
            _tokenSource?.Cancel();

            if (_socket != null)
            {
                try
                {
                    _socket?.Dispose();
                }
                catch (ObjectDisposedException) { }
            }

            if (_tokenSource != null)
            {
                try
                {
                    _tokenSource.Dispose();
                }
                catch (ObjectDisposedException) { }
            }

            if (_receivingTask != null)
            {
                await _receivingTask.ConfigureAwait(false);
            }

            _socket        = null;
            _tokenSource   = null;
            _receivingTask = null;
        }
Exemple #8
0
        //penser gestion erreur
        public static int TrouverPort(int nmbreTentatives)
        {
            int port = -1;
            int i =0;
            IPAddress ip = GetMyLocalIp();
            RandomManager rm = new RandomManager();
            while(port==-1 &&i<nmbreTentatives)
            {
                int t = rm.GetInt(65000);
                try
                {
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint tempo = new IPEndPoint(ip, t);
                    s.Bind(tempo);
                    s.Dispose();

                    port = t;
                }
                catch
                {

                    i++;
                }
            }
            return port;
        }
 public void CloseConnection()
 {
     try
     {
         if (WorkSocket != null)
         {
             if (WorkSocket.Connected)
             {
                 try
                 {
                     WorkSocket.Shutdown(System.Net.Sockets.SocketShutdown.Send);
                 }
                 catch (Exception ex)
                 {
                 }
                 WorkSocket.Close();
                 OnConnectionClosed(System.EventArgs.Empty);
             }
             if (WorkSocket != null)
             {
                 WorkSocket.Dispose();
                 WorkSocket = null;
             }
         }
     }
     catch (Exception ex)
     {
     }
 }
Exemple #10
0
 public bool ResetSocket()
 {
     if (_connectState != NetworkClientState.Closed)
     {
         _connectState = NetworkClientState.Closed;
         try
         {
             if (_socket.Connected)
             {
                 _socket.Shutdown(SocketShutdown.Both);
                 _socket.Dispose();
             }
         }
         finally
         {
             _socket.Close();
             _socket = null;
         }
         _byteArray.Destroy();
         _byteArray = null;
         return(true);
     }
     if (_unityInvoke != null)
     {
         _unityInvoke.Dispose();
         _unityInvoke = null;
     }
     _isCalled = true;
     return(false);
 }
Exemple #11
0
        private async Task<bool> waitForDataToBecomeAvailable(int numofmillisecondstowait, Socket youtubeSock)
        {
            return await Task<bool>.Run(() =>
            {
                var startTime = DateTime.Now;
                var i = 0;
                TimeSpan totTime;

                while (youtubeSock.Available == 0 && i++ < 150000)
                {
                    //System.Threading.Thread.Sleep(1);

                    if ((totTime = DateTime.Now.Subtract(startTime)).TotalMilliseconds > numofmillisecondstowait)
                    {
                        if (youtubeSock.Connected)
                        {
                            youtubeSock.Shutdown(SocketShutdown.Both);
                        }

                        youtubeSock.Close();
                        youtubeSock.Dispose();
                        LogError("\nwaitForDataToBecomeAvailable() - Dropping http request. Request data took more than 1 sec to send data.\n");

                        return false;
                    }
                };

                return true;
            });
        }
Exemple #12
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         RawSocket.Dispose();
     }
 }
Exemple #13
0
        static void Run()
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress HostIp = IPAddress.Parse("127.0.0.1");
            socket.Connect(HostIp, 2626);

            BlinkConn conn = Blink.NewConnection(socket, 1024 * 1024, "D:/", Guid.NewGuid().ToString(), 0.001f, null, null);

            if (conn != null)
            {
                Console.WriteLine("Test Send String...");
                for (int i = 0; i <= 50; i++)
                {
                    string str = "Test String:" + i;
                    conn.Send(str);
                    Console.WriteLine(str);
                    Thread.Sleep(2);
                    if (IsExit)
                    {
                        conn.Dispose();
                        socket.Shutdown(SocketShutdown.Both);
                        socket.Dispose();
                        socket.Close();
                        return;
                    }
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// 连接到远程端
        /// </summary>
        /// <param name="remoteEndPoint">远程端</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns></returns>
        private SocketError ConnectInternal(EndPoint remoteEndPoint)
        {
            if (remoteEndPoint == null)
            {
                throw new ArgumentNullException();
            }

            if (this.IsConnected == true)
            {
                return(SocketError.IsConnected);
            }

            var addressFamily = AddressFamily.InterNetwork;

            if (remoteEndPoint.AddressFamily != AddressFamily.Unspecified)
            {
                addressFamily = remoteEndPoint.AddressFamily;
            }
            var socket = new System.Net.Sockets.Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect(remoteEndPoint);
                this.session.SetSocket(socket);
                this.session.SetKeepAlive(this.KeepAlivePeriod);
                return(SocketError.Success);
            }
            catch (SocketException ex)
            {
                socket.Dispose();
                return(ex.SocketErrorCode);
            }
        }
Exemple #15
0
        public static Task CreateServerAsync(Func<Socket, Uri, Task> funcAsync, out IPEndPoint localEndPoint, Options options = null)
        {
            options = options ?? new Options();
            try
            {
                var server = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                server.Bind(new IPEndPoint(options.Address, 0));
                server.Listen(options.ListenBacklog);

                localEndPoint = (IPEndPoint)server.LocalEndPoint;
                string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ? 
                    $"[{localEndPoint.Address}]" :
                    localEndPoint.Address.ToString();
                var url = new Uri($"{(options.UseSsl ? "https" : "http")}://{host}:{localEndPoint.Port}/");

                return funcAsync(server, url).ContinueWith(t =>
                {
                    server.Dispose();
                    t.GetAwaiter().GetResult();
                }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
            }
            catch (Exception e)
            {
                localEndPoint = null;
                return Task.FromException(e);
            }
        }
Exemple #16
0
        public bool Send(byte[] packet, int port)
        {
            Socket socket = null;

            try
            {
                socket = new Socket(
                            AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp);

                socket.SetSocketOption(
                                SocketOptionLevel.Socket,
                                SocketOptionName.ReceiveTimeout,
                                2000);

                var hostEntry = Dns.Resolve(SnmpKeys.RECEIVER_IP);

                var endPoint = new IPEndPoint(hostEntry.AddressList[0], port);

                socket.SendTo(packet, packet.Length, SocketFlags.None, endPoint);

                return true;
            }
            catch (SocketException)
            {
                return false;
            }
            finally
            {
                if (socket != null)
                    socket.Dispose();
            }
        }
Exemple #17
0
        private static async void Reconnect()
        {
            _client2.Dispose();
            _client2 = null;

            bool reconnected = false;

            while (!reconnected)
            {
                try
                {
                    if (_client2 == null)
                    {
                        _client2 = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    }
                    _client2.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ModemPort));
                    reconnected = true;
                }
                catch (Exception ex)
                {
                    await Task.Delay(10000);

                    Console.WriteLine(ex);
                    continue;
                }
            }

            Task.Run(() => { Process(); });
        }
		public async Task Connect(string hostname, int port, Action notifyWhenClosed, int index)
		{
			_index = index;
			var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
			var addresses = Dns.GetHostAddresses(hostname);
			var started = false;

			foreach (var ipAddress in addresses)
			{
				if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
				{
					started = true;
					try
					{
						await socket.ConnectTaskAsync(new IPEndPoint(ipAddress, port));
					}
					catch (Exception)
					{
						socket.Dispose();
						throw;
					}
					break;
				}
			}

			if (!started) throw new Exception("Invalid hostname " + hostname); // ipv6 not supported yet

			WireStreams(socket, notifyWhenClosed);
		}
Exemple #19
0
        private Socket SOCKET; //receive socket

        #endregion Fields

        #region Methods

        public void Begin()
        {
            connect:
            SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404);
            Console.WriteLine("S104 establish a link successfully, try to receive...");

            RCV_THREAD = new System.Threading.Thread(BeginReceive);
            RCV_THREAD.Start(SOCKET);

            while (true)
            {
                System.Threading.Thread.Sleep(4000);
                this.Send_UFram(Uflag.testfr_active);
                if (RCVD_NUM >= 20000)
                {
                    SOCKET.Shutdown(SocketShutdown.Receive);
                    RCV_THREAD.Abort();
                    System.Threading.Thread.Sleep(4000);
                    SOCKET.Shutdown(SocketShutdown.Send);
                    SOCKET.Dispose();

                    RCVD_NUM = 0;
                    goto connect;
                }
                if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4))
                {
                    this.Send_SFram(RCVD_NUM);
                    Console.WriteLine("overtime send S fram...");
                }
            }
        }
        protected AbstractSocketChannel(IChannel parent, Socket socket)
            : base(parent)
        {
            this.Socket = socket;
            this.state = StateFlags.Open;

            try
            {
                this.Socket.Blocking = false;
            }
            catch (SocketException ex)
            {
                try
                {
                    socket.Dispose();
                }
                catch (SocketException ex2)
                {
                    if (Logger.WarnEnabled)
                    {
                        Logger.Warn("Failed to close a partially initialized socket.", ex2);
                    }
                }

                throw new ChannelException("Failed to enter non-blocking mode.", ex);
            }
        }
Exemple #21
0
 public static void FullClose(this System.Net.Sockets.Socket s)
 {
     try
     {
         s.Shutdown(SocketShutdown.Both);
     }
     catch (Exception)
     {
     }
     try
     {
         s.Disconnect(false);
     }
     catch (Exception)
     {
     }
     try
     {
         s.Close();
     }
     catch (Exception)
     {
     }
     try
     {
         s.Dispose();
     }
     catch (Exception)
     {
     }
 }
Exemple #22
0
        public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
        {
            if (ipAddress == null) throw new ArgumentNullException("ipAddress");
            if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
            if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");

            var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                retVal.ExclusiveAddressUse = false;
                retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
                retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), _LocalIP));
                retVal.MulticastLoopback = true;

                return new UdpSocket(retVal, localPort, _LocalIP.ToString());
            }
            catch
            {
                if (retVal != null)
                    retVal.Dispose();

                throw;
            }
        }
Exemple #23
0
        public static async Task<IDisposableConnection<ArraySegment<byte>>> CreateConnection(
            EndPoint endpoint,
            SocketType socketType = SocketType.Stream,
            ProtocolType protocolType = ProtocolType.Tcp)
        {
            var socket = new Socket(socketType, protocolType);
            bool disposeSocket = false;
            try
            {                
                using (SocketAwaitableEventArgs args = new SocketAwaitableEventArgs())
                {
                    args.RemoteEndPoint = endpoint;
                    await socket.ConnectSocketAsync(args);
                }
            }
            catch (Exception)
            {
                disposeSocket = true;
                throw;
            }
            finally
            {
                if (disposeSocket)
                {
                    socket.Dispose();
                    socket = null;
                }
            }

            return socket.ToConnection();
        }
Exemple #24
0
        public void Dispose()
        {
            try
            {
                AddClient    = null;
                RemoveClient = null;
                DataChange   = null;
                DataRecive   = null;
                DataSent     = null;

                if (ListenerSocker != null)
                {
                    ListenerSocker.Shutdown(SocketShutdown.Both);
                    if (ListenerSocker.Connected)
                    {
                        ListenerSocker.Disconnect(true);
                    }
                    ListenerSocker.Close();
                    ListenerSocker.Dispose();
                }
                for (int i = 0; i < Connections.Count; i++)
                {
                    Connections[i].Close();
                    Connections[i].Dispose();
                }
            }
            catch { }

            ListenerSocker = null;
            Connections    = null;

            Log.Log.GetLog().Info(this, "Dispose");

            GC.SuppressFinalize(this);
        }
Exemple #25
0
 private Socket SendingSocketCreator(IPEndPoint target)
 {
     var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         s.Connect(target);
         // Prep the socket so it will reset on close and won't Nagle
         s.LingerState = new LingerOption(true, 0);
         s.NoDelay = true;
         WriteConnectionPreemble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket
         // Start an asynch receive off of the socket to detect closure
         var foo = new byte[4];
         s.BeginReceive(foo, 0, 1, SocketFlags.None, ReceiveCallback,
             new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this));
         NetworkingStatisticsGroup.OnOpenedSendingSocket();
     }
     catch (Exception)
     {
         try
         {
             s.Dispose();
         }
         catch (Exception)
         {
             // ignore
         }
         throw;
     }
     return s;
 }
 public static void Dispose(Action disposeCallback = null)
 {
     _cancellationTocken.Cancel();
     foreach (string id in DicSockectConnection.Keys)
     {
         SocketConnection currSocketConnection;
         if (DicSockectConnection.TryGetValue(id, out currSocketConnection))
         {
             currSocketConnection.Disconnect();
         }
     }
     DicSockectConnection.Clear();
     Task.Run(() =>//解决主线程直接调用报错
     {
         ShowMsg("socket closed");
     });
     if (disposeCallback != null)
     {
         disposeCallback.Invoke();
     }
     else
     {
         Sktconfig?.DisposeCallback?.Invoke();
     }
     GC.Collect();
     ServerSocketListenner.Dispose();
 }
Exemple #27
0
        private void Shutdown(Exception shutdownReason)
        {
            lock (_shutdownLock)
            {
                if (_socketDisposed)
                {
                    return;
                }

                // Make sure to close the connection only after the _aborted flag is set.
                // Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when
                // a BadHttpRequestException is thrown instead of a TaskCanceledException.
                _socketDisposed = true;

                // shutdownReason should only be null if the output was completed gracefully, so no one should ever
                // ever observe the nondescript ConnectionAbortedException except for connection middleware attempting
                // to half close the connection which is currently unsupported.
                _shutdownReason = shutdownReason ?? new ConnectionAbortedException("The Socket transport's send loop completed gracefully.");

                _trace.ConnectionWriteFin(ConnectionId, _shutdownReason.Message);

                try
                {
                    // Try to gracefully close the socket even for aborts to match libuv behavior.
                    _socket.Shutdown(SocketShutdown.Both);
                }
                catch
                {
                    // Ignore any errors from Socket.Shutdown() since we're tearing down the connection anyway.
                }

                _socket.Dispose();
            }
        }
        private void Socket_Completed_Receive(object sender, SocketAsyncEventArgs e)
        {
            System.Net.Sockets.Socket socket = null;
            try
            {
                e.Completed -= this.Socket_Completed_Receive;
                socket       = ((System.Net.Sockets.Socket)sender);
                if (e.SocketError == SocketError.Success)
                {
                    var buffer     = (byte[])e.Buffer;
                    var socketArgs = new SocketAsyncEventArgs();
                    socketArgs.RemoteEndPoint = e.RemoteEndPoint;

                    socketArgs.SetBuffer(buffer, 0, buffer.Length);
                    try
                    {
                        socketArgs.Completed += Socket_Completed_ProcessResult;

                        //Sometimes ReceiveAsync doesn't receive any data (UDP packet loss?)
                        //which can leave us in a hung state. Setup a 1 second timer
                        //here to close the socket, which will cancel the request
                        //and raise the completed event with an OperationAbandoned
                        //error code if we haven't already completed.
#if SUPPORTS_TASKDELAY
                        var waitTask = System.Threading.Tasks.Task.Delay(1000);
#else
                        var waitTask = TaskEx.Delay(1000);
#endif
                        waitTask.ContinueWith(
                            (pt) =>
                        {
                            var receiveComplete = (bool)(socketArgs.UserToken ?? false);
                            if (!receiveComplete)
                            {
                                socket?.Dispose();
                            }
                        }
                            );
                        if (!socket.ReceiveAsync(socketArgs))
                        {
                            Socket_Completed_ProcessResult(socket, socketArgs);
                        }
                    }
                    catch
                    {
                        socketArgs.Completed -= this.Socket_Completed_ProcessResult;
                        throw;
                    }
                }
                else
                {
                    throw NtpNetworkExceptionFromSocketArgs(e);
                }
            }
            catch (Exception ex)
            {
                OnErrorOccurredAndDisposeSocket(ex, socket);
            }
        }
 private Action<IAsyncResult> OnAsyncCompleteAction(Socket socket)
 {
     return a =>
     {
         socket.Close();
         socket.Dispose();
     };
 }
 private AsyncCallback OnAsyncCompleteCallback(Socket socket)
 {
     return a =>
         {
             socket.Close();
             socket.Dispose();
         };
 }
Exemple #31
0
        private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
        {
            var connected = false;
            var cancelled = false;
            var timedOut = false;

            using (var registration = cancellationToken.Register(() => { if (!connected) { cancelled = true; try { socket.Dispose(); } catch { } } }))
            using (var timer = new Timer(_ => { if (!connected) { timedOut = true; try { socket.Dispose(); } catch { } } }, null, _settings.ConnectTimeout, Timeout.InfiniteTimeSpan))
            {
                try
                {
                    var dnsEndPoint = endPoint as DnsEndPoint;
                    if (dnsEndPoint != null)
                    {
                        // mono doesn't support DnsEndPoint in its BeginConnect method.
                        socket.Connect(dnsEndPoint.Host, dnsEndPoint.Port);
                    }
                    else
                    {
                        socket.Connect(endPoint);
                    }
                    connected = true;
                    return;
                }
                catch
                {
                    if (!cancelled && !timedOut)
                    {
                        throw;
                    }
                }
            }

            if (socket.Connected)
            {
                try { socket.Dispose(); } catch { }
            }

            cancellationToken.ThrowIfCancellationRequested();
            if (timedOut)
            {
                var message = string.Format("Timed out connecting to {0}. Timeout was {1}.", endPoint, _settings.ConnectTimeout);
                throw new TimeoutException(message);
            }
        }
Exemple #32
0
 protected virtual void Dispose(bool disposing)
 {
     if (!m_disposed)
     {
         if (disposing)
         {
         }
         Disconnect();
         _socket?.Dispose();
         m_disposed = true;
     }
 }
 private static bool CheckRawSocketPermissions()
 {
     try
     {
         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
         s.Dispose();
         return true;
     }
     catch
     {
         return false;
     }
 }
Exemple #34
0
		///<summary>Sends an NTPv4 request to the passed url and returns the offset from DateTime.Now.  Returns double.MaxValue if request timed out.  Will throw exception if nistServerUrl is invalid.</summary>
		public double getTime(string nistServerUrl) {
			byte[] arrayReceivedPacket=new byte[48];
			IPAddress[] addresses=Dns.GetHostEntry(nistServerUrl).AddressList;
			IPEndPoint ipEndPoint=new IPEndPoint(addresses[0],123);
			Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
			socket.ReceiveTimeout=2000;//Two seconds.  Too short?
			socket.Connect(ipEndPoint);
			//Create packet for sending then send to NIST server.
			socket.Send(MakePacket());
			try {
				socket.Receive(arrayReceivedPacket);
			}
			catch {//Response not received before Timeout.
				socket.Shutdown(SocketShutdown.Both);
				socket.Close();
				socket.Dispose();
				string messageTextFail="NTPv4 time request from "+nistServerUrl+" timed out.";
				EventLog.WriteEntry("OpenDental",messageTextFail,EventLogEntryType.Information);
				return (double.MaxValue);
			}
			//Convert the received NTP packet to a usable time stamp.
			DateTime destination=DateTime.Now.ToUniversalTime();
			DateTime originate=RawToDateTime(arrayReceivedPacket,24);
			DateTime receive=RawToDateTime(arrayReceivedPacket,32);
			DateTime transmit=RawToDateTime(arrayReceivedPacket,40);
			double offset=(((receive-originate)-(destination-transmit)).TotalMilliseconds)/2; //Offset calculation based off Ntpv4 specification.
			//Close connection
			socket.Shutdown(SocketShutdown.Both);
			socket.Close();
			socket.Dispose();
			string messageText="NTPv4 time request received from "+nistServerUrl+"."
				+"\nOriginate:  "+originate.ToString("hh:mm:ss.fff tt")
				+"\nReceive:  "+receive.ToString("hh:mm:ss.fff tt")
				+"\nTransmit:  "+transmit.ToString("hh:mm:ss.fff tt")
				+"\nDestination:  "+destination.ToString("hh:mm:ss.fff tt")
				+"\nOffset:  "+offset+" milliseconds";
			EventLog.WriteEntry("OpenDental",messageText,EventLogEntryType.Information);
			return offset;
		}
Exemple #35
0
 protected void Dispose(bool disposing)
 {
     if (mySocket != null)
     {
         mySocket.Close();
         mySocket.Dispose();
         mySocket = null;
     }
     if (reciveThread != null)
     {
         reciveThread.Abort();
         reciveThread = null;
     }
 }
Exemple #36
0
 public static void TcpConnect(IPAddress address, int port, Action<Exception, Socket> cb)
 {
     Socket sock = null;
     try {
         sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         sock.BeginConnect (address, port, (ar) => {
             try {
                 sock.EndConnect (ar);
                 sock.NoDelay = true;
             } catch (Exception ex) {
                 sock.Dispose ();
                 cb (ex, null);
                 return;
             }
             cb (null, sock);
         }, null);
     } catch (Exception ex) {
         if (sock != null)
             sock.Dispose ();
         cb (ex, null);
         return;
     }
 }
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            _clientSocket?.Dispose();
            _socketMessageHandler.Dispose();
            _readEventArgs?.Dispose();
            MessageReceived = null;
            Connected       = null;
        }
Exemple #38
0
		public override byte[] SendAndReceive(byte[] data, int attempts = 1)
		{
			var socket = new Socket(RemoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
			try
			{
				try
				{
					if (LocalEndPoint != null)
						socket.Bind(LocalEndPoint);
					socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout);
				}
				catch (Exception e)
				{
					throw new CfnException("Could not bind to local endpoint", e);
				}




				var exceptions = new List<Exception>();
				while (attempts != 0)
				{
					attempts--;
					try
					{
						socket.SendTo(data, RemoteEndPoint);

						var tempBuffer = new byte[512]; //Maximum UDP Size
						int receivedData = socket.Receive(tempBuffer);
						var responseData = new byte[receivedData];
						Array.Copy(tempBuffer, responseData, receivedData);
						return responseData;
					}
					catch (Exception e)
					{
						if (attempts == 0 && exceptions.Count == 0)
							throw new CfnException(e);
						exceptions.Add(e);
					}
				}

				throw new CfnMergedException("Multiple errors occured while sending data to " + RemoteEndPoint.Address + ":" + RemoteEndPoint.Port, exceptions.Select(x => new CfnException(x)));
			}
			finally
			{
				socket.Close();
				socket.Dispose();
			}
		}
Exemple #39
0
        public IUdpSocket CreateUdpSocket(int localPort)
        {
            var netSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
            try
            {
                return new UdpSocket(netSocket, localPort, _LocalIPAddress);
            }
            catch
            {
                if (netSocket != null)
                    netSocket.Dispose();

                throw;
            }
        }
 public static ISocket Open(IPEndPoint endPoint, int connectTimeout = Timeout.Infinite, int receiveTimeout = Timeout.Infinite, int sendTimeout = Timeout.Infinite) {
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true, SendTimeout = sendTimeout, ReceiveTimeout = receiveTimeout };
     var ar = socket.BeginConnect(endPoint, null, null);
     if(ar.AsyncWaitHandle.WaitOne(connectTimeout)) {
         socket.EndConnect(ar);
     } else {
         try {
             socket.Shutdown(SocketShutdown.Both);
             socket.Close();
             socket.Dispose();
         } catch { }
         throw new SocketException(10060);
     }
     return new SocketAdapter(socket);
 }
Exemple #41
0
        private void checkAccess()
        {
            UdpClient UDP = new UdpClient();
            IPEndPoint receiverIP = new IPEndPoint(IPAddress.Parse(IP), 810);       //create end point

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);     //create new socket
            IPEndPoint bindIP = new IPEndPoint(IPAddress.Any, 811);     //end point to listen response

            UDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            UDP.Send(Password, Password.Length, receiverIP);        //send message
            UDP.Close();

            try
            {
                socket.Bind(bindIP);        //listen  811 port
            }
            catch { }

            IPEndPoint senderIP = new IPEndPoint(IPAddress.Any, 0);     //end point to answer
            EndPoint Remote = (EndPoint)(senderIP);

            byte[] data = new byte[256];      //array that will save ping message
            int size = 0;

            do
            {
                if (socket.Available > 0)
                {
                    size = socket.ReceiveFrom(data, ref Remote);       //read message to data
                    Array.Resize(ref data, size);
                    if (System.Text.Encoding.Default.GetString(data) != "false")
                    {
                        Volume = Convert.ToSingle(System.Text.Encoding.Default.GetString(data));    //mute sound on sender
                        checkFlag = true;
                        break;
                    }
                    else
                    {
                        checkFlag = false;
                        break;
                    }
                }
                Thread.CurrentThread.Join(0);
            } while (true);
            socket.Dispose();
            socket.Close();
            Thrd.Abort();
        }
Exemple #42
0
        public async Task Reconnect()
        {
            if (_tcpClient != null)
            {
                _tcpClient.Client.Dispose();
                _tcpClient = new TcpClient();
                await _tcpClient.ConnectAsync(_socketSettings.Address, _socketSettings.Port);
            }

            if (_unixClient != null)
            {
                _unixClient.Dispose();
                _unixClient = new System.Net.Sockets.Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                _unixClient.Connect(_unixEndpoint);
            }
        }
Exemple #43
0
        // Closes the network connection.
        public void Stop()
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            _serverSocket?.Dispose();
            _active       = false;
            _serverSocket = null;

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(this);
            }
        }
Exemple #44
0
        public void AddClient(Socket socket)
        {
            if (_clients.Count >= _maxClients)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                socket.Dispose();
            }
            else
            {
                var Client = new GameClient(GenerateClientID(), socket);
                _clients.Add(Client.ID, Client);

                Logging.WriteFancyLine("Accepted new client [" + Client.ID + "] from " + Client.IP);
            }
        }
        public static void Listener(int port)
        {
            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.ReceiveTimeout = 5000; // receive timout 5 seconds
            listener.SendTimeout = 5000; // send timeout 5 seconds 

            listener.Bind(new IPEndPoint(IPAddress.Any, port));
            listener.Listen(backlog: 15);

            WriteLine($"listener started on port {port}");

            var cts = new CancellationTokenSource();


            var tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
            tf.StartNew(() =>  // listener task
            {
                WriteLine("listener task started");
                while (true)
                {
                    if (cts.Token.IsCancellationRequested)
                    {
                        cts.Token.ThrowIfCancellationRequested();
                        break;
                    }
                    WriteLine("waiting for accept");
                    Socket client = listener.Accept();
                    if (!client.Connected)
                    {
                        WriteLine("not connected");
                        continue;
                    }
                    WriteLine($"client connected local address {((IPEndPoint)client.LocalEndPoint).Address} and port {((IPEndPoint)client.LocalEndPoint).Port}, remote address {((IPEndPoint)client.RemoteEndPoint).Address} and port {((IPEndPoint)client.RemoteEndPoint).Port}");

                    Task t = CommunicateWithClientUsingSocketAsync(client);

                }
                listener.Dispose();
                WriteLine("Listener task closing");

            }, cts.Token);

            WriteLine("Press return to exit");
            ReadLine();
            cts.Cancel();

        }
Exemple #46
0
 internal static void SafeCloseSocket(System.Net.Sockets.Socket socket)
 {
     try
     {
         socket.Disconnect(false);
     }
     catch
     {
     }
     try
     {
         socket.Dispose();
     }
     catch
     {
     }
 }
Exemple #47
0
        public static void Stop()
        {
            try
            {
                _client2?.Disconnect(false);
                _client2?.Dispose();

                _stopReceiving = true;
                _reconnected   = true;
                _timer?.Stop();
                _timer?.Dispose();
            }
            catch (Exception ex)
            {
                LogUtils.Error($"{ex}");
            }
        }
Exemple #48
0
 internal static void SafeCloseSocket(System.Net.Sockets.Socket socket)
 {
     try
     {
         socket.Shutdown(SocketShutdown.Both);
     }
     catch
     {
     }
     try
     {
         socket.Dispose();
     }
     catch
     {
     }
 }
        public void _deviceListListen()
        {
            data = new byte[256];      //array that will save ping message
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);     //create new socket

            IPEndPoint receiverIP = new IPEndPoint(IPAddress.Any, 810);     //end point to listen 810

            try
            {
                socket.Bind(receiverIP);        //listen  810 port
            }
            catch { }

            IPEndPoint senderIP = new IPEndPoint(IPAddress.Any, 0);     //end point to answer
            EndPoint Remote = (EndPoint)(senderIP);
            double size = 0;
            do
            {
                if (socket.Available > 0)
                {
                    try
                    {
                        size = socket.ReceiveFrom(data, ref Remote);       //read message to data
                    }
                    catch{}

                    Array.Resize(ref data, (int)size);
                    if (System.Text.Encoding.Default.GetString(data) == "ping")
                        socket.SendTo(data, data.Length, SocketFlags.None, _getHost(Remote.ToString(), 811));    //send answer to 811 port
                    else
                    {
                        IP = Remote.ToString().Remove(Remote.ToString().IndexOf(":"), Remote.ToString().Length - Remote.ToString().IndexOf(":"));
                        break;
                    }
                }
                Thread.Sleep(100);
                Thread.CurrentThread.Join(0);
            } while (true);

            socket.Dispose();
            socket.Close();

            //passCheckReceiver = new _passCheckReceiver(IP, Password);
        }
Exemple #50
0
        public Task ConnectAsync(Uri url, CancellationToken cancellationToken)
        {
            _url = url;

            var args = new SocketAsyncEventArgs
            {
                RemoteEndPoint = new DnsEndPoint(url.Host, url.Port)
            };

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (null != Interlocked.CompareExchange(ref _socket, socket, null))
            {
                socket.Dispose();
                throw new InvalidOperationException("The socket is in use");
            }

            return DoAsync(_socket.ConnectAsync, args, cancellationToken);
        }
Exemple #51
0
        private static bool tryPort(int port)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            var endpoint = new IPEndPoint(IPAddress.Any, port);

            try
            {
                socket.Bind(endpoint);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                socket.Dispose();
            }

        }
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (_socket != null)
                    {
                        if (_socket.Connected)
                        {
                            _socket.Close();
                        }
                        _socket.Dispose();
                    }

                    _tcpListener.Stop();
                }

                disposedValue = true;
            }
        }
 public override void Close()
 {
     if (!Monitor.TryEnter(this))
     {
         Timer closer = null;
         closer = new Timer((state) =>
         {
             closer.Dispose();
             this.Close();
         });
         closer.Change(300, 0);
     }
     else
     {
         try
         {
             try
             {
                 Socket socket = this.m_server;
                 if (socket != null)
                 {
                     Shutdown(socket);
                     try
                     {
                         socket.Close();
                         socket.Dispose();
                     }
                     catch (Exception) { }
                     this.m_server = null;
                 }
             }
             catch (Exception) { }
         }
         finally
         {
             Monitor.Exit(this);
         }
     }
     base.Close();
 }
Exemple #54
0
    /// <summary>
    /// Остановка сервера
    /// </summary>
    public void Stop()
    {
        try
        {
            if (!_isListen)
            {
                Log.Logger.Information("Сокет сервер уже выключен");
                return;
            }

            _acceptConnectionsTokenSource.Cancel();
            _acceptConnections.Wait();
            _acceptConnections = null;
            _clientController.DisconnectAllClients();
            _serverSocket.Close();
            _serverSocket.Dispose();
            Log.Logger.Information("Сокет сервер выключен");
        }
        catch (Exception ex)
        {
            Log.Logger.Information($"Произошла ошибка при выключении сервера: {ex}");
        }
    }
Exemple #55
0
        private void OnNewConnection(IAsyncResult asyncResult)
        {
            System.Net.Sockets.Socket client = _listenerSocket.EndAccept(asyncResult);
            client.NoDelay = true;

            _listenerSocket.BeginAccept(OnNewConnection, this);

            switch (_sessionType)
            {
            case EnumSessionType.Telnet:
            {
                _logger.Info($"Accepting incoming Telnet connection from {client.RemoteEndPoint}...");
                var telnetSession = new TelnetSession(client);
                break;
            }

            case EnumSessionType.Rlogin:
            {
                if (((IPEndPoint)client.RemoteEndPoint).Address.ToString() != _configuration["Rlogin.RemoteIP"])
                {
                    _logger.Info(
                        $"Rejecting incoming Rlogin connection from unauthorized Remote Host: {client.RemoteEndPoint}");
                    client.Close();
                    client.Dispose();
                    return;
                }

                _logger.Info($"Accepting incoming Rlogin connection from {client.RemoteEndPoint}...");
                var rloginSession = new RloginSession(client, _moduleIdentifier);
                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public static void FullClose(this System.Net.Sockets.Socket s)
        {
            try
            {
                s.Shutdown(SocketShutdown.Both);
            }
            catch
            {
                // ignored
            }

            try
            {
                s.Disconnect(false);
            }
            catch
            {
                // ignored
            }
            try
            {
                s.Close();
            }
            catch
            {
                // ignored
            }
            try
            {
                s.Dispose();
            }
            catch
            {
                // ignored
            }
        }
Exemple #57
0
 public void Dispose()
 {
     _socket.Shutdown(SocketShutdown.Send);
     _socket.Dispose();
 }
Exemple #58
0
 public void Dispose()
 {
     Console.WriteLine("===== Disposing native socket");
     nativeSocket.Dispose();
 }
Exemple #59
0
        /// <summary>
        /// Start accepting socket connections.
        /// </summary>
        private void StartAccept()
        {
            try
            {
                // Clear last error.
                ClearLastError();

                do
                {
                    // Set the event to nonsignaled state.
                    _connAvailable.Reset();

                    // Do not allow any more clients
                    // if maximum is reached.
                    if (_clientCount < _maxNumClients)
                    {
                        System.Net.Sockets.Socket clientSocket = null;

                        // Create a new client connection handler for the current
                        // tcp client attempting to connect to the server. Creates
                        // a new channel from the client to the server.
                        clientSocket = _socket.Accept();

                        // Create a new instance of the server context type.
                        object state = null;
                        state = clientSocket;

                        Thread acceptContext = null;
                        try
                        {
                            // Start a new worker thread.
                            acceptContext = new Thread(CreateServerContext);
                            acceptContext.IsBackground = true;
                            acceptContext.Start(state);
                        }
                        catch (Exception ex)
                        {
                            if (clientSocket != null)
                            {
                                clientSocket.Dispose();
                            }

                            acceptContext = null;
                            SetLastError(ex);
                        }

                        Thread.Sleep(20);
                    }
                    else
                    {
                        // Blocks the current thread until a
                        // connection becomes available.
                        _connAvailable.WaitOne();
                    }
                } while (true);
            }
            catch (Exception ex)
            {
                // Stop listening.
                StopListening();

                SetLastError(ex);

                // Trigger the stop listening event.
                StopListeningEvent(ex);
            }
        }
Exemple #60
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Set the web socket state to closed.
                if (_context != null)
                {
                    _context.SocketState = SocketState.Closed;
                }

                // Release the receive and send spin wait handler.
                Interlocked.Exchange(ref _exitWaitReceiveIndicator, 0);
                Interlocked.Exchange(ref _exitWaitSendIndicator, 0);
                Interlocked.Exchange(ref _isContextActive, 0);

                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Close the connection.
                    CloseEx();

                    if (_socket != null)
                    {
                        _socket.Dispose();
                    }

                    if (_sslStream != null)
                    {
                        _sslStream.Dispose();
                    }

                    if (_networkStream != null)
                    {
                        _networkStream.Dispose();
                    }

                    if (_requestBuffer != null)
                    {
                        _requestBuffer.Dispose();
                    }

                    if (_responseBuffer != null)
                    {
                        _responseBuffer.Dispose();
                    }

                    if (_requestStream != null)
                    {
                        _requestStream.Dispose();
                    }

                    if (_responseStream != null)
                    {
                        _responseStream.Dispose();
                    }

                    if (_context != null)
                    {
                        if (_context.ContextState != null)
                        {
                            // If the current state context
                            // implements IDisposable then
                            // dispose of the resources.
                            if (_context.ContextState is IDisposable)
                            {
                                IDisposable disposable = (IDisposable)_context.ContextState;
                                disposable.Dispose();
                            }
                        }
                        _context.Dispose();
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _socket                = null;
                _sslStream             = null;
                _networkStream         = null;
                _x509Certificate       = null;
                _endConnectionCallback = null;

                _requestBuffer  = null;
                _responseBuffer = null;

                _requestStream  = null;
                _responseStream = null;

                _request  = null;
                _response = null;

                _context.ContextState = null;
                _context = null;
            }
        }