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


C# Socket.Disconnect方法代码示例

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


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

示例1: Disconnect_Success

        public void Disconnect_Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0);
            using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnCompleted;
                args.UserToken = completed;
                args.RemoteEndPoint = server1.EndPoint;
                args.DisconnectReuseSocket = true;

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);

                    client.Disconnect(true);

                    args.RemoteEndPoint = server2.EndPoint;

                    Assert.True(client.ConnectAsync(args));
                    completed.WaitOne();
                    Assert.Equal(SocketError.Success, args.SocketError);
                }
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:30,代码来源:DisconnectTest.cs

示例2: Success

        public void Success()
        {
            AutoResetEvent completed = new AutoResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                int port, port1;
                using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port))
                using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port1))
                {
                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.Completed += OnCompleted;
                    args.UserToken = completed;
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
                    args.DisconnectReuseSocket = true;

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

                    Assert.True(client.ConnectAsync(args));
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);

                    client.Disconnect(true);

                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port1);

                    Assert.True(client.ConnectAsync(args));
                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);

                    client.Dispose();
                }
            }
        }
开发者ID:shrutigarg,项目名称:corefx,代码行数:34,代码来源:Disconnect.cs

示例3: Disconnect_NonWindows_NotSupported

 public void Disconnect_NonWindows_NotSupported()
 {
     using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         Assert.Throws<PlatformNotSupportedException>(() => client.Disconnect(true));
     }
 }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:DisconnectTest.cs

示例4: DisconnectAsync_Throws_PlatformNotSupported

        public void DisconnectAsync_Throws_PlatformNotSupported()
        {
            IPAddress address = null;
            if (Socket.OSSupportsIPv4)
            {
                address = IPAddress.Loopback;
            }
            else if (Socket.OSSupportsIPv6)
            {
                address = IPAddress.IPv6Loopback;
            }
            else
            {
                return;
            }

            int port;
            using (SocketTestServer.SocketTestServerFactory(address, out port))
            {
                var completed = new AutoResetEvent(false);

                var args = new SocketAsyncEventArgs
                {
                    UserToken = completed,
                    RemoteEndPoint = new IPEndPoint(address, port),
                    DisconnectReuseSocket = true
                };
                args.Completed += OnCompleted;

                var client = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                Assert.True(client.ConnectAsync(args));
                Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
                Assert.Equal<SocketError>(SocketError.Success, args.SocketError);

                Assert.Throws<PlatformNotSupportedException>(() => client.Disconnect(true));

                client.Dispose();
            }
        }
开发者ID:shrutigarg,项目名称:corefx,代码行数:39,代码来源:Disconnect.cs

示例5: Handler

        private void Handler()
        {
            bool recvRequest = true;
            string EOL = "\r\n";

            string requestPayload = "";
            string requestTempLine = "";
            List<string> requestLines = new List<string>();
            byte[] requestBuffer = new byte[1];
            byte[] responseBuffer = new byte[1];

            requestLines.Clear();

            try
            {
                while (recvRequest)
                {
                    this.clientSocket.Receive(requestBuffer);
                    string fromByte = ASCIIEncoding.ASCII.GetString(requestBuffer);
                    requestPayload += fromByte;
                    requestTempLine += fromByte;

                    if (requestTempLine.EndsWith(EOL))
                    {
                        requestLines.Add(requestTempLine.Trim());
                        requestTempLine = "";
                    }

                    if (requestPayload.EndsWith(EOL + EOL))
                    {
                        recvRequest = false;
                    }
                }
                Console.WriteLine("Raw Request Received...");
                Console.WriteLine(requestPayload);
                string remoteHost = requestLines[0].Split(' ')[1].Replace("http://", "").Split('/')[0];
                string requestFile = requestLines[0].Replace("http://", "").Replace(remoteHost, "");
                requestLines[0] = requestFile;

                requestPayload = "";
                foreach (string line in requestLines)
                {
                    requestPayload += line;
                    requestPayload += EOL;
                }

                Socket destServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                destServerSocket.Connect(remoteHost, 80);
                destServerSocket.Send(ASCIIEncoding.ASCII.GetBytes(requestPayload));

                while (destServerSocket.Receive(responseBuffer) != 0)
                {
                    this.clientSocket.Send(responseBuffer);
                }

                destServerSocket.Disconnect(false);
                destServerSocket.Dispose();
                this.clientSocket.Disconnect(false);
                this.clientSocket.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Occured: " + e.Message);
            }
        }
开发者ID:hacktune,项目名称:CS_SRV,代码行数:65,代码来源:Program.cs

示例6: DropConnection

 private void DropConnection(Socket remote)
 {
     try
     {
         if (remote.Connected)
         {
             remote.Disconnect(true);
         }
     }
     catch (Exception e)
     {
         if (e is SocketException)
         {
             Debug.LogError("Socket ErrorCode:" + ((SocketException)e).SocketErrorCode);
         }
     }
 }
开发者ID:RaskoSmash,项目名称:TankBattle,代码行数:17,代码来源:SocketListener.cs

示例7: Poll

    private void Poll(object state)
    {
        lock (PollSync) // pattern taken from DefaultNodeLocator, presumably to avoid two threads from colliding in here
        {
            var instances = RoleEnvironment.Roles[memcachedRoleName].Instances.ToList(); // potential memcached servers according to Windows Azure

            var changed = false;

            foreach (var instance in instances)
            {
                if (!nodes.ContainsKey(instance.Id)) // new server
                {
                    var endpoint = instance.InstanceEndpoints[memcachedEndpointName].IPEndpoint;

                    // if and only if server's alive (accepts socket connection)
                    using (var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                    {
                        try
                        {
                            socket.Connect(endpoint);
                            if (socket.Connected)
                            {
                                socket.Disconnect(false);

                                // add the server
                                nodes[instance.Id] = new MemcachedNode(endpoint, this.configuration.SocketPool);
                                nodes[instance.Id].Failed += Poll;
                                changed = true;
                            }
                        }
                        catch (SocketException) { }
                    }
                }
            }

            foreach (var key in nodes.Keys.ToList())
            {
                // prune dead nodes (either found to be dead by trying to use them or by dropping off Windows Azure's list)
                if (!nodes[key].IsAlive || !instances.Any(i => i.Id == key))
                {
                    nodes[key].Failed -= Poll;
                    nodes.Remove(key);
                    changed = true;
                }
            }

            if (changed)
            {
                // Note: Enyim documentation says it's important to always use the same order (for consistent hashing)
                nodeLocator.Initialize(nodes.OrderBy(p => p.Key).Select(p => p.Value).ToList());
            }
        }
    }
开发者ID:CarpDeus,项目名称:Azure-MOOP-Framework,代码行数:53,代码来源:ClientHelpers.cs

示例8: CreatedSocketCanBeDisconnected

 public void CreatedSocketCanBeDisconnected()
 {
     var socket = new Socket<IAudioStream>();
     socket.Disconnect();
     socket.IsConnected.Should().Be.False();
 }
开发者ID:JohnStov,项目名称:WinHill.Audio,代码行数:6,代码来源:SocketTests.cs

示例9: Start

 private void Start()
 {
     if (!EmoEngineInst.IsStarted)
     {
         EmoEngineInst.Cq = new int[18];
         this.engine.EmoEngineConnected += new EmoEngine.EmoEngineConnectedEventHandler(EmoEngineInst.engine_EmoEngineConnected);
         this.engine.EmoEngineDisconnected += new EmoEngine.EmoEngineDisconnectedEventHandler(EmoEngineInst.engine_EmoEngineDisconnected);
         this.engine.EmoEngineEmoStateUpdated += new EmoEngine.EmoEngineEmoStateUpdatedEventHandler(EmoEngineInst.engine_EmoEngineEmoStateUpdated);
         string hostNameOrAddress = "127.0.0.1";
         int port = 3008;
         IPAddress iPAddress = Dns.GetHostAddresses(hostNameOrAddress)[0];
         IPAddress address = IPAddress.Parse("127.0.0.1");
         Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         IPEndPoint remoteEP = new IPEndPoint(address, port);
         try
         {
             socket.Connect(remoteEP);
         }
         catch (SocketException var_6_9C)
         {
         }
         if (socket.Connected)
         {
             socket.Shutdown(SocketShutdown.Both);
             socket.Disconnect(true);
             this.engine.RemoteConnect("127.0.0.1", 3008);
         }
         else
         {
             this.engine.Connect();
         }
         EmoEngineInst.IsStarted = true;
     }
 }
开发者ID:AnotherAltr,项目名称:EmotivSDK,代码行数:34,代码来源:EmoEngineInst.cs

示例10: DisconnectingSocketDisconnectsPlug

        public void DisconnectingSocketDisconnectsPlug()
        {
            var stream = Substitute.For<IAudioStream>();
            var plug = new Plug<IAudioStream>(stream);
            var socket = new Socket<IAudioStream>();

            socket.ConnectTo(plug);

            socket.Disconnect();
            plug.IsConnected.Should().Be.False();
        }
开发者ID:JohnStov,项目名称:WinHill.Audio,代码行数:11,代码来源:SocketTests.cs

示例11: receivefile

            /// <summary>
            /// Receives a file using the CedLib protocol. (sender must be using CedLib.Networking.sendfile)
            /// </summary>
            /// <param name="bacon">The socket to use, will be disconnected after file is received, but can be reused.</param>
            /// <param name="FileInfo">The file to save to.</param>
            /// <param name="contentheader">The CedLib content header as received from the remote party.</param>
            /// <param name="Console">The CedLib formConsole to spam info to while transferring.</param>
            public static void receivefile(Socket bacon, FileInfo FileInfo, CedLibContentheader contentheader, formConsole Console)
            {
                int chunksize = Globals.chunksize * 1024;
                Console.WriteLine("Chunksize is set to " + chunksize);
                byte[] receivebytes = new byte[chunksize];
                //If done initializing stuff for the receive, send 'OK!' to signal the start of the transfer
                Console.WriteLine("Sending response to header");
                sendstring(bacon, "OK!\n Continue to send me the file");
                if (!waitfordata(bacon, 30000, Console))
                    throw new Exception("Time out while waiting for sender to begin transfer.");
                BinaryWriter bwriter = new BinaryWriter(File.Open(FileInfo.FullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read));
                System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
                swatch.Start();
                Console.Write(string.Format("Receiving file from {0}..", bacon.RemoteEndPoint));
                long receivedcount = 0;
                int lastreceive = 1;
                while (lastreceive > 0 && bacon.Connected && receivedcount <= contentheader.ContentLength)
                {
                    if (bacon.Connected)
                        lastreceive = bacon.Receive(receivebytes, chunksize, SocketFlags.None);
                    else
                    {
                        Console.Write("Remote party disconnected. ");
                        break;
                    }
                    bwriter.Write(receivebytes, 0, lastreceive);
                    bwriter.Flush();
                    Console.Write(".");
                    receivedcount += lastreceive;
                }
                bwriter.Flush();
                bwriter.Close();
                bool verified = false;
                swatch.Stop();
                bacon.Shutdown(SocketShutdown.Both);
                bacon.Disconnect(true);
                Console.WriteLine("Done, verifying MD5..");
                if (contentheader.FileSum != "")
                {
                    string newsum = misc_usefulfunctions.GetMD5HashFromFile(FileInfo.FullName);
                    if (newsum != contentheader.FileSum)
                        throw new Exception(string.Format("File corrupted during transfer! Expected sum {0} But got sum {1}", contentheader.FileSum, newsum));
                    verified = true;
                }
                else
                    Console.WriteLine("Warning: No MD5 summary found in content header, cannot verify data!");

                float speedinKB = ((receivedcount / 1024.0f) / (swatch.ElapsedMilliseconds / 1000.0f));
                if (verified)
                    Console.WriteLine(string.Format("Verified MD5!\nSummary: received {0} bytes in {1} milliseconds! ({2}KB/s)", new object[] { receivedcount, swatch.ElapsedMilliseconds, speedinKB }));
                else
                    Console.WriteLine(string.Format("Summary: received {0} bytes in {1} milliseconds! ({2}KB/s)", new object[] { receivedcount, swatch.ElapsedMilliseconds, speedinKB }));
            }
开发者ID:xarinatan,项目名称:CedLib,代码行数:60,代码来源:Networking.cs

示例12: sendfile

            /// <summary>
            /// Sends a file using the CedLib protocol to a receiving party (which should also be using CedLib)
            /// </summary>
            /// <param name="bacon">Provided socket, must be connected. Will be disconnected after sending is done, however can be reused.</param>
            /// <param name="FileInfo">The file to send</param>
            /// <param name="Console">The CedLib console to spam information to.</param>
            public static void sendfile(Socket bacon, FileInfo FileInfo, formConsole Console)
            {
                //First establish the filesize to send and notify the receiver
                StringBuilder contentheaderbuilder = new StringBuilder();
                string filemd5 = misc_usefulfunctions.GetMD5HashFromFile(FileInfo.FullName);
                contentheaderbuilder.AppendFormat("Contentheader:File\nCedLibProtVersion|:{0}\nContentlength|:{1}\nFileSum|:{2}\nFileName|:{3}", new object[] { CedLib.Globals.netversion, FileInfo.Length, filemd5, FileInfo.Name });
                Console.WriteLine("Sending content header");
                sendstring(bacon, contentheaderbuilder.ToString());
                if (!waitfordata(bacon, 30000, Console))
                    throw new Exception("Time out while waiting for response to header");
                string response = receivestring(bacon, Console);
                if (response.StartsWith("OK!"))
                {
                    Console.Write("Sending file..");
                    BinaryReader breader = new BinaryReader(File.Open(FileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                    NetworkStream nstream = new NetworkStream(bacon, FileAccess.Write, false);
                    int blocksize = Globals.chunksize * 1024;
                    Console.WriteLine("Chunksize is set to " + blocksize);
                    System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
                    swatch.Start();
                    byte[] sendbytes;
                    for (long i = 0; i < Math.Ceiling(new decimal(FileInfo.Length / blocksize)) + 1; i++)
                    {
                        sendbytes = breader.ReadBytes(blocksize);
                        nstream.Write(sendbytes, 0, sendbytes.Length);

                        Console.Write(".");
                    }
                    swatch.Stop();
                    float speedinKB = ((FileInfo.Length / 1024.0f) / (swatch.ElapsedMilliseconds / 1000.0f));
                    breader.Close();
                    nstream.Flush();
                    nstream.Close();
                    bacon.Shutdown(SocketShutdown.Both);
                    bacon.Disconnect(true);
                    Console.WriteLine(string.Format("Done! Sent {0}bytes in {1} milliseconds.({2}KB/s)", new object[3] { FileInfo.Length, swatch.ElapsedMilliseconds, speedinKB }));
                }
                else
                    throw new Exception("Remote endpoint threw error, filetransfer failed.", new Exception(response));
            }
开发者ID:xarinatan,项目名称:CedLib,代码行数:46,代码来源:Networking.cs

示例13: receivebytes

 /// <summary>
 /// Receives bytes from a remote party and puts them in a memory stream. (as opposed to a file)
 /// </summary>
 /// <param name="bacon">Socket to receive from</param>
 /// <param name="cHeader">CedLib contentheader (needed for bytescount)</param>
 /// <param name="Console">The CedLib formConsole to spam relevant info to.</param>
 /// <returns>Memorystream filled with bytes from remote party.</returns>
 public static MemoryStream receivebytes(Socket bacon, CedLibContentheader cHeader, formConsole Console)
 {
     MemoryStream memstream = new MemoryStream();
     int chunksize = 1024 * 1024;
     byte[] receivebytes = new byte[chunksize];
     //If done initializing stuff for the receive, send 'OK!' to signal the start of the transfer
     Console.WriteLine("Sending response to header");
     sendstring(bacon, "OK!\n Continue to send me the bytes");
     if (!waitfordata(bacon, 30000, Console))
         throw new Exception("Time out while waiting for sender to begin transfer.");
     System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
     swatch.Start();
     Console.Write("Receiving file..");
     long receivedcount = 0;
     int lastreceive = 1;
     while (lastreceive > 0 && bacon.Connected && receivedcount <= cHeader.ContentLength)
     {
         if (bacon.Connected)
             lastreceive = bacon.Receive(receivebytes, chunksize, SocketFlags.None);
         else
         {
             Console.Write("Remote party disconnected. ");
             break;
         }
         memstream.Write(receivebytes, 0, lastreceive);
         Console.Write(".");
         receivedcount += lastreceive;
     }
     swatch.Stop();
     bacon.Shutdown(SocketShutdown.Both);
     bacon.Disconnect(true);
     float speedinKB = ((receivedcount / 1024.0f) / (swatch.ElapsedMilliseconds / 1000.0f));
     Console.WriteLine(string.Format("Done! received {0} bytes in {1} milliseconds! ({2}KB/s)", new object[] { receivedcount, swatch.ElapsedMilliseconds, speedinKB }));
     return memstream;
 }
开发者ID:xarinatan,项目名称:CedLib,代码行数:42,代码来源:Networking.cs

示例14: sendbytes

 /// <summary>
 /// Sends give nbytes to remote party.
 /// </summary>
 /// <param name="bacon">Socket to serve the snacks and bytes over.</param>
 /// <param name="bytestosend">The snacks and bytes.</param>
 /// <param name="Console">Cedlib formConsole to spam progress reports to.</param>
 public static void sendbytes(Socket bacon, byte[] bytestosend, formConsole Console)
 {
     //First establish the filesize and a filesum to send and notify the receiver
     StringBuilder contentheaderbuilder = new StringBuilder();
     contentheaderbuilder.AppendFormat("Contentheader:File\nCedLibProtVersion|:{0}\nContentlength|:{1}", new object[] { CedLib.Globals.netversion, bytestosend.Length });
     Console.WriteLine("Sending content header");
     sendstring(bacon, contentheaderbuilder.ToString());
     if (!waitfordata(bacon, 30000, Console))
         throw new Exception("Time out while waiting for response to header");
     string response = receivestring(bacon, Console);
     System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
     swatch.Start();
     if (response.StartsWith("OK!"))
     {
         Console.Write("Sending file..");
         NetworkStream nstream = new NetworkStream(bacon, FileAccess.Write, false);
         nstream.Write(bytestosend, 0, bytestosend.Length);
         nstream.Flush();
         swatch.Stop();
         float speedinKB = ((bytestosend.Length / 1024.0f) / (swatch.ElapsedMilliseconds / 1000.0f));
         nstream.Close();
         bacon.Shutdown(SocketShutdown.Both);
         bacon.Disconnect(true);
         Console.WriteLine(string.Format("Done! Sent {0}bytes in {1} milliseconds.({2}KB/s)", new object[3] { bytestosend.Length, swatch.ElapsedMilliseconds, speedinKB }));
     }
     else
         throw new Exception("Remote endpoint threw error, filetransfer failed.", new Exception(response));
 }
开发者ID:xarinatan,项目名称:CedLib,代码行数:34,代码来源:Networking.cs


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