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


C# Sockets.NetworkStream类代码示例

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


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

示例1: Agent

        private Thread ziThread; //处理客户端请求的线程

        #endregion Fields

        #region Constructors

        public Agent(TcpClient client, NetworkStream streamToClient, string DataSourceIpOrPortA, string DataSourceIpOrPortB)
        {
            this.client = client;
            this.streamToClient = streamToClient;
            this.DataSourceIpOrPortA = DataSourceIpOrPortA;
            this.DataSourceIpOrPortB = DataSourceIpOrPortB;
        }
开发者ID:find-life,项目名称:KIOSKWindowService,代码行数:13,代码来源:Agent.cs

示例2: ConnectionContext

 public ConnectionContext(NetworkStream clientStream, string connString, TcpTestServer3 server, TaskLoggingHelper log)
 {
     this.clientStream = clientStream;
     this.connString = connString;
     this.tcpServer = server;
     this.log = log;
 }
开发者ID:ericlemes,项目名称:IntegrationTests,代码行数:7,代码来源:ConnectionContext.cs

示例3: ReadVisibleLevelState

        /// <summary>
        /// Reads a partially observable level state update from the server.
        /// </summary>
        private async Task ReadVisibleLevelState(NetworkStream stream)
        {
            Time = await _stream.ReadUInt64();
            PlayerPosition = await _stream.ReadPosition();

            // removed lock
            int roomCount = await _stream.ReadInt32();
            for (int i = 0; i < roomCount; ++i)
            {
                // Each room is identified by its rectangle.
                var rect = await _stream.ReadRectangle();

                var vis = _visibility.FirstOrDefault(x => x.Rect == rect);

                if (vis == null)
                {
                    vis = new RoomVisibility(rect);
                    _visibility.Add(vis);
                }

                int tileCount = await _stream.ReadInt32();
                for (int j = 0; j < tileCount; ++j)
                {
                    var pos = await _stream.ReadPosition();
                    vis.Reveal(pos, await TileAppearance.Read(pos, stream), Time);
                }
            }

            LoadedLevel = true;


            Program.Draw(this);

            Interface.Display.Write(0, 0, Time.ToString());
        }
开发者ID:Tamschi,项目名称:FacePuncher,代码行数:38,代码来源:ServerConnection.cs

示例4: SendTransportPacket

 public static async Task SendTransportPacket(NetworkStream sw, TransportPacketType type, byte[] Data)
 {
     TransportPacket tp = new TransportPacket(Data, type, Constants.TransportVersion);
     byte[] msg = PacketCodec.CreateTransportPacket(tp);
     sw.Write(msg, 0, msg.Length);
     await sw.FlushAsync();
 }
开发者ID:dipamchang,项目名称:tnetd-open,代码行数:7,代码来源:PacketSender.cs

示例5: OutboundPacket

        public OutboundPacket(NetworkStream stream, String command)
        {
            command = "!1" + command;
            int dataSize = command.Length + _packetFooter.Length;
            int packetSize = _packetHeaderTotalSize + dataSize;

            byte[] message = new byte[packetSize];
            int pos = 0;

            foreach (byte b in _packetHeader)
                message[pos++] = b;

            foreach (byte b in BitConverter.GetBytes(dataSize).Reverse())
                message[pos++] = b;

            message[pos++] = _protocolVersion;
            pos += 3;

            foreach (byte b in System.Text.Encoding.ASCII.GetBytes(command))
                message[pos++] = b;

            foreach (byte b in _packetFooter)
                message[pos++] = b;
            stream.Write(message, 0, message.Length);
            try { System.Threading.Thread.Sleep(100); } catch (Exception) { }
        }
开发者ID:kbrantley,项目名称:ReceiverWhisperer,代码行数:26,代码来源:OutboundPacket.cs

示例6: Response

        internal Response(NetworkStream stream)
        {
            string response;

            m_responses = new Queue();

            do
            {
                response = GetLine(stream);

                try
                {
                    m_code = InvalidCode;
                    m_code = int.Parse(response.Substring(0, 3));
                }
                catch
                {
                    throw new InvalidResponseException("Invalid response", this);
                }

                m_responses.Enqueue(response);
            }
            while (response.Length >= 4 && response[3] == '-');

            if (m_code == ServiceUnavailable)
                throw new ServerDownException(this);
        }
开发者ID:avs009,项目名称:gsf,代码行数:27,代码来源:Response.cs

示例7: Main

 public Main(string userName, string serverSocket, NetworkStream stream)
     : this()
 {
     UserName = userName;
     ServerSocket = serverSocket;
     Stream = stream;
 }
开发者ID:escray,项目名称:SocketProgram,代码行数:7,代码来源:Main.cs

示例8: Build

        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
开发者ID:krigans,项目名称:Griffin.Framework,代码行数:36,代码来源:ClientSideSslStreamBuilder.cs

示例9: ReadMessage

        /// <summary>
        /// Blocking call to read a full Message object from a given stream
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Message ReadMessage(NetworkStream stream)
        {
            Debug.Assert(stream.CanRead);

            byte[] messageBytes = new byte[Message.MaxSize];
            byte[] sizeBytes = new byte[4];
            int bytesRead = 0;

            // Read the initial size from the stream
            while (bytesRead < 4)
            {
                bytesRead += stream.Read(sizeBytes, bytesRead, sizeBytes.Length);
            }

            int messageSize = BitConverter.ToInt32(sizeBytes, 0);
            Debug.Assert(messageSize < Message.MaxSize);
            bytesRead = 0;

            // Get the message bytes
            while (bytesRead < messageSize)
            {
                bytesRead += stream.Read(messageBytes, bytesRead, messageBytes.Length - bytesRead);
            }

            // Deserialize the message
            return Message.Deserialize(messageBytes);
        }
开发者ID:HotPrawns,项目名称:Jiemyu_Unity,代码行数:32,代码来源:MessageUtil.cs

示例10: EstablishConnectionSpecific

        /// <inheritdoc />
        protected override void EstablishConnectionSpecific()
        {
            if (btClient == null) ConnectSocket();

            //We should now be able to set the connectionInfo localEndPoint
            var localEndPoint = btClient.Client.LocalEndPoint as BluetoothEndPoint;
            localEndPoint = new BluetoothEndPoint(localEndPoint.Address, ConnectionInfo.RemoteBTEndPoint.Service, localEndPoint.Port);

            NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteEndPoint, localEndPoint);
            ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);

            btClient.Client.ReceiveBufferSize = NetworkComms.MaxReceiveBufferSizeBytes;
            btClient.Client.SendBufferSize = NetworkComms.SendBufferSizeBytes;

            //We are going to be using the networkStream quite a bit so we pull out a reference once here
            btClientNetworkStream = btClient.GetStream();
                        
            //Start listening for incoming data
            StartIncomingDataListen();

            //If the application layer protocol is enabled we handshake the connection
            if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
                ConnectionHandshake();
            else
            {
                //If there is no handshake we can now consider the connection established
                TriggerConnectionEstablishDelegates();

                //Trigger any connection setup waits
                connectionSetupWait.Set();
            }            
        }
开发者ID:MarcFletcher,项目名称:NetworkComms.Net,代码行数:33,代码来源:BluetoothConnection.cs

示例11: SslStream

 public SslStream(
   NetworkStream innerStream,
   bool leaveInnerStreamOpen,
   RemoteCertificateValidationCallback userCertificateValidationCallback
 ) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback)
 {
 }
开发者ID:fengxianqi,项目名称:Youbang,代码行数:7,代码来源:SslStream.cs

示例12: NetworkClient

 public NetworkClient(System.Net.IPAddress serverAddress, int port)
 {
     TcpClient client = new TcpClient();
     client.Connect(serverAddress, port);
     _stream = client.GetStream();
     _connected = true;
     BackgroundWorker streamWorker = new BackgroundWorker();
     streamWorker.WorkerSupportsCancellation = true;
     streamWorker.DoWork += ReadFromStream;
     streamWorker.RunWorkerCompleted += (s, a) =>
                                     {
                                         if (_connected)
                                         {
                                             streamWorker.RunWorkerAsync(_stream);
                                         }
                                     };
     streamWorker.RunWorkerAsync(_stream);
     StreamError += (ex, stream) =>
                     {
                         if (ex is IOException || ex is InvalidOperationException || ex is ObjectDisposedException)
                         {
                             _connected = false;
                             Console.WriteLine("Lost connection: {0}", ex.Message);
                             Console.Write("> ");
                         }
                         else
                         {
                             throw ex;
                         }
                     };
 }
开发者ID:Mellen,项目名称:Networking-Samples,代码行数:31,代码来源:NetworkClient.cs

示例13: btnConnect_Click

        private void btnConnect_Click(object sender, EventArgs e)
        {


            try
            {
                client = new TcpClient("127.0.0.1", 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);

                String response = sr.ReadLine();

                DelegateResponse dr = writeResponse;
                dr(response);

                randomCoordinates();

                string rawData = "Hola mundo";
                String data = stringToHexa(rawData);
                //Console.WriteLine(data);
                sw.WriteLine(data);
                sw.Flush();

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                throw;
            }
        }
开发者ID:Maldercito,项目名称:geoworks,代码行数:31,代码来源:1456388846$form1.cs

示例14: AbsTcpCommunication

 public AbsTcpCommunication(TcpClient sock)
 {
     _sock = sock;
     _socketStream = _sock.GetStream ();
     _in = new StreamReader (_socketStream);
     _out = new StreamWriter (_socketStream);
 }
开发者ID:raabmar,项目名称:The-Tangibles,代码行数:7,代码来源:AbsTcpCommunication.cs

示例15: ChatClient

 public ChatClient()
 {
     this.client = new TcpClient();
     this.stream = null;
     this.listening = false;
     this.listener = new Thread(this.listen);
 }
开发者ID:kr094,项目名称:csharp,代码行数:7,代码来源:ChatClient.cs


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