当前位置: 首页>>代码示例>>C#>>正文


C# Socket.Dispose方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Dispose方法的具体用法?C# Socket.Dispose怎么用?C# Socket.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DestorySocket

        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;
        }
开发者ID:Microshaoft,项目名称:Microshaoft.Common.Utilities.Net.4x,代码行数:28,代码来源:SocketHelper.cs

示例2: Main

        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();
        }
开发者ID:mozajik,项目名称:site_connectinfo,代码行数:31,代码来源:Program.cs

示例3: PSTUClient

 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;
     }
 }
开发者ID:vvdrak,项目名称:PSTUTestManagerRepository,代码行数:26,代码来源:PSTUClient.cs

示例4: TrouverPort

        //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;
        }
开发者ID:Chapelin,项目名称:XNAGitTest,代码行数:27,代码来源:GestionReseau.cs

示例5: Main

        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();
        }
开发者ID:guogongjun,项目名称:Blink,代码行数:31,代码来源:Program.cs

示例6: Send

        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();
            }
        }
开发者ID:CristianCK,项目名称:RawSNMP,代码行数:34,代码来源:SimpleSNMP.cs

示例7: Connect

		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);
		}
开发者ID:danielmarbach,项目名称:RabbitMqNext,代码行数:29,代码来源:SocketHolder.cs

示例8: Begin

        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...");
                }
            }
        }
开发者ID:Wave-Maker,项目名称:S104,代码行数:38,代码来源:S104.cs

示例9: Run

        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;
                    }
                }
            }
        }
开发者ID:guogongjun,项目名称:Blink,代码行数:29,代码来源:Program.cs

示例10: CreateServerAsync

        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);
            }
        }
开发者ID:charygao,项目名称:corefx,代码行数:28,代码来源:LoopbackServer.cs

示例11: CreateConnection

        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();
        }
开发者ID:headinthebox,项目名称:IoFx,代码行数:31,代码来源:SocketUtility.cs

示例12: waitForDataToBecomeAvailable

        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;
            });
        }
开发者ID:blackhatk0d3,项目名称:Mpgrabber,代码行数:30,代码来源:Mpgrabber.cs

示例13: CreateUdpMulticastSocket

        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;
            }
        }
开发者ID:sk8tz,项目名称:RSSDP,代码行数:27,代码来源:SocketFactory.cs

示例14: AbstractSocketChannel

        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);
            }
        }
开发者ID:RabbitTeam,项目名称:DotNetty,代码行数:27,代码来源:AbstractSocketChannel.cs

示例15: SendingSocketCreator

 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;
 }
开发者ID:sbambach,项目名称:orleans,代码行数:30,代码来源:SocketManager.cs


注:本文中的System.Net.Sockets.Socket.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。