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


C# NetworkStream.Dispose方法代码示例

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


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

示例1: GenerateLoad

        public static void GenerateLoad(int packetsPerBurst, int sleepMilliseconds)
        {
            IPAddress address = (from a in Dns.GetHostAddresses(Environment.MachineName)
            where a.AddressFamily == AddressFamily.InterNetwork
            select a).FirstOrDefault();

            Console.WriteLine("IP Address is: {0}", address.ToString());

            Socket listenSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(new IPEndPoint(address, Port));
            listenSocket.Listen(10);

            Socket sendSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            sendSocket.Connect(new IPEndPoint(address, Port));
            NetworkStream writeStream = new NetworkStream(sendSocket, true);

            Socket receiveSocket = listenSocket.Accept();
            NetworkStream readStream = new NetworkStream(receiveSocket, true);
            BinaryReader reader = new BinaryReader(readStream);

            byte[] buffer = new byte[PacketSize];
            while (!Console.KeyAvailable)
            {
                for (int i=0; i<packetsPerBurst; i++)
                {
                    writeStream.Write(buffer, 0, buffer.Length);
                    readStream.Read(buffer, 0, buffer.Length);
                }
                
                if (sleepMilliseconds > 0)
                {
                    Thread.Sleep(sleepMilliseconds);
                }

            }
            Console.ReadKey();

            writeStream.Dispose();
            readStream.Dispose();
            listenSocket.Dispose();
        }
开发者ID:modulexcite,项目名称:Tx,代码行数:41,代码来源:Program.cs

示例2: receiveDataAsync

        private void receiveDataAsync(NetworkStream readStream)
        {
            bool continueFlag = true;

            while (continueFlag)
            {
                byte[] buffer = new byte[1024];
                int readCount = readStream.Read(buffer, 0, 1024);
                byte[] recvBuffer = buffer.ToList().GetRange(0, readCount).ToArray();
                string receivedMessage = System.Text.Encoding.ASCII.GetString(recvBuffer);

                Console.WriteLine("ServerReceived: " + System.Text.Encoding.ASCII.GetString(recvBuffer));

                if (receivedMessage.Equals("END"))
                {
                    continueFlag = false;
                } // end if
            } // end while

            readStream.Dispose();
        }
开发者ID:RedSpiderMkV,项目名称:TestRepo,代码行数:21,代码来源:Server.cs

示例3: joinGame

        public void joinGame()
        {
            try
            {
                this.clientSocket.Connect(serverIP, serverPortNumber);
                this.clientStream = this.clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(Util.Constants.JoinRequest);
                clientStream.Write(outStream, 0, outStream.Length);
                clientStream.Dispose();
                clientStream.Flush();
                launched = true;
                this.receiveData();

            }
            catch (Exception ex)
            {
                DialogResult dr = MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (dr == DialogResult.OK)
                    Application.Exit();
                launched = false;
            }
        }
开发者ID:pubudu538,项目名称:Battle_Tanks,代码行数:22,代码来源:Communicator.cs

示例4: Listen

        public void Listen()
        {
            string msg= "";
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipEndPoint);
            newsock.Listen(10);
            Socket client = newsock.Accept();

            using (NetworkStream stream = new NetworkStream(client))
            {
                StreamReader streamReader = new StreamReader(stream);
                msg = streamReader.ReadLine();
                ServerParser serverParser = new ServerParser();
                string res = serverParser.Decode(msg);
                using (StreamWriter streamWriter = new StreamWriter(stream))
                {
                    streamWriter.WriteLine(res);
                }
                stream.Dispose();
            }
            newsock.Close();
        }
开发者ID:Alex-Klyuchnik,项目名称:UBB_Test_app,代码行数:23,代码来源:ConnectionEstablisher.cs

示例5: SendFile

        /// <summary>
        /// Отправляет файл по указанному адресу.
        /// </summary>
        /// <param name="ip">Удаленный IP-адрес.</param>
        /// <param name="port"></param>
        /// <param name="file_name">Удаленный порт.</param>
        /// <param name="exec_proc">Будет ли вызвано выполнение подпрограммы на принимающей стороне.</param>
        /// <param name="is_delete_file"></param>
        public static void SendFile(IPAddress ip, int port, string file_name, bool exec_proc = false, bool is_delete_file = false)
        {
            FileInfo file = new FileInfo(file_name);

            if (FileSize.HasValue)
            {
                FileSize = file.Length;
            }

            // Устанавливаем соединение через сокет.
            Socket socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(ip, port));
            var ns = new NetworkStream(socket);
            var fs = new FileStream(file_name, FileMode.Open, FileAccess.Read, FileShare.Read);

            ns.WriteByte((byte)(exec_proc ? MesasageType.ReveiveFileAndExecProc : MesasageType.ReceiveFile));
            fs.CopyToAsync(ns).ContinueWith((ar) =>
            {
                fs.Close();
                fs.Dispose();
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                ns.Close();
                ns.Dispose();

                if (is_delete_file)
                {
                    File.Delete(file_name);
                }
            });
        }
开发者ID:dha01,项目名称:CSharp-SimpleFileTransfer,代码行数:39,代码来源:Server.cs

示例6: SetupServerSocket

        public virtual bool SetupServerSocket()
#endif
        {
            try
            {
                //keep
                bool isSecured = false;
                string sslProtocol = "";

                //check packer
                if (SupportedChannelSerializationModes.HasFlag(ChannelSerializationMode.MessagePack))
                    DebugEx.Assert(MsgPack != null, "MessagePack serializer not provided");

                //create network stream
#if NETFX
                //Stream _netstream = new BufferedStream(new NetworkStream(base._sock, true));
                Stream _netstream = new NetworkStream(base._sock, true);

                //Wrap with a secure stream?
                if (Server.Certificate != null)
                {
                    var sslstream = new SslStream(_netstream, false);
                    try
                    {
                        //try authenticate
                        sslstream.AuthenticateAsServer(Server.Certificate, false, SslProtocols.Tls | SslProtocols.Tls12 | SslProtocols.Tls11, true);

                        //checks
                        if (!sslstream.IsAuthenticated)
                        {
                            DebugEx.Assert("Not authenticated");
                            throw new Exception("Not authenticated");
                        }
                        if (!sslstream.IsEncrypted)
                        {
                            DebugEx.Assert("No encryption");
                            throw new Exception("Not encryption");
                        }

                        //get info
                        isSecured = true;
                        sslProtocol = sslstream.SslProtocol.ToStringInvariant();

                        //use this stream from now on
                        _netstream = sslstream;
                    }
                    catch (Exception ex)
                    {
                        var msg = ex.Message;
                        if (ex.InnerException != null && ex.InnerException.Message != ex.Message)
                            msg += "  (inner msg=" + ex.InnerException.Message + ")";
                        DebugEx.TraceError("Certificate not accepted, " + msg);
                        try { Close("Certificate not accepted, " + msg); } catch { }
                        try { sslstream.Close(); base._sock.Dispose(); } catch { }
                        try { _netstream.Close(); _netstream.Dispose(); } catch { }
                        try { _sock.Close(); _sock.Dispose(); } catch { }
                        return false; //failed
                    }
                }
#endif

                //read clients packers
                var clientPackers = ChannelSerializationMode.Unkown;
                var clientPreferredPackers = ChannelSerializationMode.Unkown;
#if NETFX
                clientPackers = (ChannelSerializationMode)_netstream.ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_netstream.ReadByte();
#elif UNIVERSAL
                clientPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
#endif

                //filter packers
                clientPackers = clientPackers & SupportedChannelSerializationModes;
                clientPreferredPackers = clientPackers & clientPreferredPackers;
                var serverPreferredPackers = clientPackers & PreferredChannelSerializationModes;
                var commonPreferredPackers = clientPreferredPackers & serverPreferredPackers;

                //choose packer
                if ((_ChannelSerializationMode = _choosePacker(commonPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(serverPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPackers)) == ChannelSerializationMode.Unkown)
                {
                    DebugEx.TraceError("Could not decide on packer.");
                    try { Close("Could not decide on packer."); } catch { }
#if NETFX
                    try { _netstream?.Close(); _netstream?.Dispose(); } catch { }
                    try { _sock?.Close(); _sock?.Dispose(); } catch { }
#elif UNIVERSAL
                    try { _sock?.Dispose(); } catch { }
#endif
                    return false; //failed
                }

                //write packer
#if NETFX
                var _nodelay = _sock.NoDelay;
                _sock.NoDelay = true; //Disable the Nagle Algorithm
                _netstream.WriteByte((byte)_ChannelSerializationMode);
//.........这里部分代码省略.........
开发者ID:yodiwo,项目名称:plegma,代码行数:101,代码来源:ServerChannel.cs

示例7: transfer_file

        public void transfer_file(string filename, string ip_addr)
        {
            Thread.Sleep(1000);
            try
            {
                Console.WriteLine("transfering file to :" + ip_addr);
                TcpClient tcpClient = new TcpClient(ip_addr, 7890);
                nStream = tcpClient.GetStream();
                writeImageData = new StreamWriter(nStream);

                //Change the filename here. If you change the file type,
                //you must change it on the Server Project too.

                FileStream fs = File.OpenRead(filename);
                byte[] ImageData = new byte[fs.Length];
                fs.Read(ImageData, 0, ImageData.Length);

                Base64ImageData = Convert.ToBase64String(ImageData);

                int startIndex = 0;

                Console.WriteLine("Transfering Data...");

                while (Done == false)
                {
                    while (startIndex < Base64ImageData.Length)
                    {
                        try
                        {
                            BlockData = Base64ImageData.Substring(startIndex, 100);
                            writeImageData.WriteLine(BlockData);
                            writeImageData.Flush();
                            startIndex += 100;
                        }
                        catch (Exception)
                        {
                            RemainingStringLength = Base64ImageData.Length - startIndex;
                            BlockData = Base64ImageData.Substring(startIndex, RemainingStringLength);
                            writeImageData.WriteLine(BlockData);
                            writeImageData.Flush();
                            Done = true;
                            break;
                        }
                    }
                }

                writeImageData.Close();
                tcpClient.Close();
                fs.Close();
                fs.Dispose();
                nStream.Close();
                nStream.Dispose();
                nStream = null;
                tcpClient.Close();
                ImageData = null;
                Base64ImageData = null;

                Console.WriteLine("Transfer Complete");
                MessageBox.Show("File Transfer to " + ip_addr +" is Completed");
            }
            catch (Exception er)
            {
                Console.WriteLine("Unable to connect to server");
                MessageBox.Show("Unable to connect to server");
                Console.WriteLine(er.Message);
            }
        }
开发者ID:kishordgupta,项目名称:control_pc_via_lan_csharp,代码行数:67,代码来源:Form1.cs

示例8: Listen

        private async void Listen()
        {
            _socket.Listen(backlog: 2);
            while (!_disposed)
            {
                Http2ServerSession session = null;
                Socket clientSocket = null;
                Stream stream = null;
                try
                {
                    clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, (Func<IAsyncResult, Socket>)_socket.EndAccept, null);
                    stream = new NetworkStream(clientSocket, ownsSocket: true);

                    X509Certificate clientCert = null;

                    if (_enableSsl)
                    {
                        SslStream sslStream = new SslStream(stream);
                        await sslStream.AuthenticateAsServerAsync(_serverCert, clientCertificateRequired: false, enabledSslProtocols: _sslProtocols, checkCertificateRevocation: false);
                        clientCert = sslStream.RemoteCertificate;
                        stream = sslStream;
                    }

                    // TODO: At this point we could read the first bit of the first byte received on this connection to determine if it is a HTTP/1.1 or 2.0 request.

                    IPEndPoint localEndPoint = (IPEndPoint)clientSocket.LocalEndPoint;
                    IPEndPoint remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;

                    TransportInformation transportInfo = new TransportInformation()
                    {
                        ClientCertificate = clientCert,
                        LocalPort = localEndPoint.Port.ToString(CultureInfo.InvariantCulture),
                        RemotePort = remoteEndPoint.Port.ToString(CultureInfo.InvariantCulture),
                    };

                    // Side effect of using dual mode sockets, the IPv4 addresses look like 0::ffff:127.0.0.1.
                    if (localEndPoint.Address.IsIPv4MappedToIPv6)
                    {
                        transportInfo.LocalIpAddress = localEndPoint.Address.MapToIPv4().ToString();
                    }
                    else
                    {
                        transportInfo.LocalIpAddress = localEndPoint.Address.ToString();
                    }

                    if (remoteEndPoint.Address.IsIPv4MappedToIPv6)
                    {
                        transportInfo.RemoteIpAddress = remoteEndPoint.Address.MapToIPv4().ToString();
                    }
                    else
                    {
                        transportInfo.RemoteIpAddress = remoteEndPoint.Address.ToString();
                    }

                    session = new Http2ServerSession(_next, transportInfo);
                    // TODO: awaiting here will only let us accept the next connection/session after the current one finishes.
                    await session.Start(stream, CancellationToken.None);
                }
                catch (ProtocolViolationException)
                {
                    // Handshake failure, most likely do to receiving a HTTP/1.1 text request.
                }
                catch (SocketException)
                {
                    // Disconnect?
                }
                catch (ObjectDisposedException)
                {
                    Dispose();
                }
                catch (Exception)
                {
                    Dispose();
                    throw;
                }
                finally
                {
                    if (session != null)
                    {
                        session.Dispose();
                    }

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

                    if (clientSocket != null)
                    {
                        clientSocket.Dispose();
                    }
                }
            }
        }
开发者ID:Tratcher,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:94,代码来源:Http2SocketServer.cs

示例9: AcceptTcpConnection

        private void AcceptTcpConnection()
        {
            Socket socket1 = null;
            try
            {
                Encoding encoding1 = Encoding.GetEncoding(0x6faf);
                string text1;
                while (true)
                {
                    socket1 = localListen.AcceptSocket();
                    byte[] buffer1 = new byte[0x43];
                    if ((socket1 != null) && socket1.Connected)
                    {
                        NetworkStream stream1 = new NetworkStream(socket1);
                        stream1.ReadTimeout = 0x3e8;
                        try
                        {
                            stream1.Read(buffer1, 0, buffer1.Length);
                        }
                        catch (Exception)
                        {
                        }

                        text1 = encoding1.GetString(buffer1, 0, buffer1.Length);
                        if ((text1.IndexOf("BitTorrent protocol") >= 0) && (text1.IndexOf(encoding1.GetString(this.currentTorrentFile.InfoHash)) >= 0))
                        {
                            byte[] buffer2 = createHandshakeResponse();
                            stream1.Write(buffer2, 0, buffer2.Length);
                        }

                        socket1.Close();
                        stream1.Close();
                        stream1.Dispose();
                    }
                }
            }
            catch (Exception exception1)
            {
                AddLogLine("Error in AcceptTcpConnection(): " + exception1.Message);
                return;
            }
            finally
            {
                if (socket1 != null)
                {
                    socket1.Close();
                    AddLogLine("Closed socket");
                }

                CloseTcpListener();
            }
        }
开发者ID:NikolayIT,项目名称:RatioMaster.NET,代码行数:52,代码来源:RM.cs

示例10: connectionThread

        private void connectionThread()
        {
            try{
                Console.WriteLine("Connecting to: "+Host+":"+Port);

                client.ConnectAsync(Host, Port);
                while(Timeout>0)
                {
                    if(client.Connected) break;
                    Timeout--;
                    Thread.Sleep(1);
                }

                if(!client.Connected) {
                    throw new Exception("Cant connect to: "+Host+":"+Port+" Timeout");
                }

                Console.WriteLine("Connected to: "+Host+":"+Port);

                stream = client.GetStream();
                if(stream == null) throw new Exception("Cant get stream for: "+Host+":"+Port+" ");

                if(OnConnectEvent!=null) OnConnectEvent(this,new EventArgs());

                while(run)
                {
                    //Tutaj tylko testujemy
                    if (!client.Connected) {
                        //Jakis ewvent

                        run = false;
                    }

                    Thread.Sleep(1000);
                }

            } catch(Exception e) {
                Console.WriteLine ("Error: "+e.Message);
                return;
            }

            Console.WriteLine("Disconecting: "+Host+":"+Port);
            if (client.Connected) {
                if (stream != null) {
                    stream.Close ();
                    stream.Dispose ();
                    stream = null;
                }
                client.Close ();
                client = null;
            }

            Console.WriteLine("Disconected: "+Host+":"+Port);
            if(OnDisconnectEvent!=null) OnDisconnectEvent(this,new EventArgs());
        }
开发者ID:rastabaddon,项目名称:QCCTV,代码行数:55,代码来源:QTcpClient.cs

示例11: receive_file_tcp

        private void receive_file_tcp(String devicename, String ipadd, int port)
        {
            try
            {
                _buffer = new byte[63 * 1024];

                _tcplistener = new TcpListener(IPAddress.Any, port);
                _tcplistener.Start();
                _tcpclient = _tcplistener.AcceptTcpClient();
                _netstream = _tcpclient.GetStream();
                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                while ((_length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    _filestream.Write(_buffer, 0, _length);
                }

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _tcpclient.Close();
                _tcplistener.Stop();

                System.Threading.Thread.Sleep(1000);

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:37,代码来源:Wifi_agent.cs

示例12: ActiveWebProbeRaw

        private static bool ActiveWebProbeRaw()
        {
            using (var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    var remoteHost = new IPEndPoint(Dns.GetHostEntry(ActiveWebProbeHost).AddressList[0], 80);
                    bool result = Connect(clientSocket, remoteHost, 5000);
                    if (result == false)
                    {
                        clientSocket.Close();
                        return false;
                    }

                    _netStream = new NetworkStream(clientSocket, true);

                    var sb = new StringBuilder();
                    sb.Append("GET http://");
                    sb.Append(ActiveWebProbeHost);
                    sb.Append("/");
                    sb.Append(ActiveWebProbePath);
                    sb.AppendLine(" HTTP/1.1");
                    sb.Append("Host: ");
                    sb.AppendLine(ActiveWebProbeHost);
                    sb.AppendLine("Connection: close");
                    sb.AppendLine();

                    byte[] buffer = Encoding.UTF8.GetBytes(sb.ToString());

                    _netStream.Write(buffer, 0, buffer.Length);

                    buffer = GetResponse(clientSocket);

                    var response = new string(Encoding.UTF8.GetChars(buffer));

                    return EndsWith(response, ActiveWebProbeContent);
                }

                catch (SocketException socketException)
                {
                    if (socketException.ErrorCode == 10060)
                    {
                        Log.WriteString(LogMessageType.Warning, "No internet connection. (www.msftncsi.com unreachable)");
                    }
                }

                catch (Exception exception)
                {
                    Log.WriteException(exception, "");
                }

                finally
                {
                    if (_netStream != null)
                    {
                        _netStream.Close();
                        _netStream.Dispose();
                    }

                    clientSocket.Close();
                }
            }
            return false;
        }
开发者ID:karlvonkries,项目名称:sc-firmwareapp,代码行数:64,代码来源:Internet.cs

示例13: receive_file

        public override void receive_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();
                scan_transfer_speed();                

                _bluetooth_guid = Guid.Parse(bluid);
                _bluetooth_listener = new BluetoothListener(_bluetooth_guid);
                _bluetooth_listener.Start();

                _bluetooth_client = _bluetooth_listener.AcceptBluetoothClient();
                _netstream = _bluetooth_client.GetStream();

                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                int length;
                _buffer = new byte[65000];
                
                while ((length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    while (_writing) { }

                    _count_received_bytes += length;

                    _filestream.Write(_buffer, 0, length);
                }

                _timer_ts.Close();
                _stopwatch.Stop();

                int _transferspeed = _count_received_bytes / 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), "kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message);

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _bluetooth_listener.Stop();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }               
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:56,代码来源:Bluetooth_agent.cs

示例14: Close

        private void Close(NetworkStream ns)
        {
            try
            {
                if (ns != null)
                {
                    ns.Close();
                    ns.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            if (IsServer)
                lock (syncobj)
                {
                    for (int i = 0; i < members.Count;)
                    {
                        if (members [i].Connection == ns || members [i].Connection == null ||
                            !members [i].Connection.CanRead || !members [i].Connection.CanWrite)
                        {
                            SendLeave(members [i].ID);
                            members.RemoveAt(i);
                        }
                        else
                            i++;
                    }
                }
        }
开发者ID:muranoya,项目名称:MonoMacChat,代码行数:32,代码来源:ChatController.cs

示例15: ProcessAccept

        /// <summary>
        /// Callback method for asynchronous accept operation.
        /// </summary>
        private void ProcessAccept(SocketAsyncEventArgs acceptArgs)
        {
            TransportProvider<Socket> client = new TransportProvider<Socket>();
            SocketAsyncEventArgs receiveArgs = null;
            WindowsPrincipal clientPrincipal = null;
            TcpClientInfo clientInfo;

            try
            {
                if (CurrentState == ServerState.NotRunning)
                    return;

                // If acceptArgs was disposed, m_acceptArgs will either
                // be null or another instance of SocketAsyncEventArgs.
                // This check will tell us whether it's been disposed.
                if ((object)acceptArgs != m_acceptArgs)
                    return;

                if (acceptArgs.SocketError != SocketError.Success)
                {
                    // Error is unrecoverable.
                    // We need to make sure to restart the
                    // server before we throw the error.
                    SocketError error = acceptArgs.SocketError;
                    ThreadPool.QueueUserWorkItem(state => ReStart());
                    throw new SocketException((int)error);
                }

                // Process the newly connected client.
                client.Provider = acceptArgs.AcceptSocket;
                client.Provider.ReceiveBufferSize = ReceiveBufferSize;

                // Set up SocketAsyncEventArgs for receive operations.
                receiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                receiveArgs.Completed += ReceiveHandler;

                // Return to accepting new connections.
                acceptArgs.AcceptSocket = null;

                if (!m_tcpServer.AcceptAsync(acceptArgs))
                {
                    ThreadPool.QueueUserWorkItem(state => ProcessAccept(acceptArgs));
                }

#if !MONO
                // Authenticate the connected client Windows credentials.
                if (m_integratedSecurity)
                {
                    NetworkStream socketStream = null;
                    NegotiateStream authenticationStream = null;
                    try
                    {
                        socketStream = new NetworkStream(client.Provider);
                        authenticationStream = new NegotiateStream(socketStream);
                        authenticationStream.AuthenticateAsServer();

                        if (authenticationStream.RemoteIdentity is WindowsIdentity)
                            clientPrincipal = new WindowsPrincipal((WindowsIdentity)authenticationStream.RemoteIdentity);
                    }
                    catch (InvalidCredentialException)
                    {
                        if (!m_ignoreInvalidCredentials)
                            throw;
                    }
                    finally
                    {
                        if (socketStream != null)
                            socketStream.Dispose();

                        if (authenticationStream != null)
                            authenticationStream.Dispose();
                    }
                }
#endif

                if (MaxClientConnections != -1 && ClientIDs.Length >= MaxClientConnections)
                {
                    // Reject client connection since limit has been reached.
                    TerminateConnection(client, receiveArgs, false);
                }
                else
                {
                    // We can proceed further with receiving data from the client.
                    clientInfo = new TcpClientInfo
                    {
                        Client = client,
                        SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(),
                        SendLock = new object(),
                        SendQueue = new ConcurrentQueue<TcpServerPayload>(),
                        ClientPrincipal = clientPrincipal
                    };

                    // Create operation to dump send queue payloads when the queue grows too large.
                    clientInfo.DumpPayloadsOperation = new ShortSynchronizedOperation(() =>
                    {
                        TcpServerPayload payload;

//.........这里部分代码省略.........
开发者ID:rmc00,项目名称:gsf,代码行数:101,代码来源:TcpServer.cs


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