• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Sockets.NetworkStream类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

 private async void ReadAsync(NetworkStream stream)
 {
     byte[] buffer = new byte[100];
     while (true)
     {
         try
         {
             int length = await stream.ReadAsync(buffer, 0, buffer.Length);
             Invoke(new MethodInvoker(delegate
             {
                 outputText.Append(buffer, length);
             }));
         }
         catch
         {
             if (this.Visible)
             { // we're not being closed
                 Invoke(new MethodInvoker(delegate
                 {
                     Stop();
                 }));
             }
             break;
         }
     }
 }
开发者ID:tewarid,项目名称:NetTools,代码行数:26,代码来源:MainForm.cs


示例13: Write

        public override void Write(ref NetworkStream netstream)
        {
            using (Stream stream = new MemoryStream())
            {
                // write id
                stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);

                // write body size
                stream.Write(BitConverter.GetBytes(0), 0, 4);

                // write isAdult
                stream.WriteByte(BitConverter.GetBytes(this.isAdult)[0]);

                // write UnderFifteen
                stream.WriteByte(BitConverter.GetBytes(this.UnderFifteen)[0]);

                // write Family
                stream.WriteByte(BitConverter.GetBytes(this.Family)[0]);

                // write Status
                stream.WriteByte(this.Status);

                // write LastDay
                stream.Write(BitConverter.GetBytes(this.LastDay), 0, 2);

                // write PayType
                stream.WriteByte(this.PayType);

                // copy stream to netstream
                stream.Position = 0;
                stream.CopyTo(netstream);
            }
        }
开发者ID:RudyJ,项目名称:ODK-DarkEmu,代码行数:33,代码来源:LCLoginOK.cs


示例14: Connection

        internal Connection(Socket ClientSocket, NetworkStream ClientStream)
        {
            this.ClientSocket = ClientSocket;
            this.ClientStream = ClientStream;

            this.Reader = new WebSocketFrameReader(ClientStream);
        }
开发者ID:Vengarioth,项目名称:WebSocketsImplementation,代码行数:7,代码来源:Connection.cs


示例15: Auth

 internal override bool Auth(NetworkStream stream)
 {
     var reader = new BinaryReader(stream);
     var writer = new BinaryWriter(stream);
     try
     {
         int ver = reader.ReadByte();
         if(ver != 0x05)
         {
             throw new Exception();
         }
         string login = reader.ReadString();
         string password = reader.ReadString();
         bool result = _callback(login, password);
         if(result)
         {
             writer.Write(new byte[] { 0x05, 0x00 });
             return true;
         }
         writer.Write(new byte[] { 0x05, 0xFF });
     }
     catch(IOException)
     {}
     catch
     {
         writer.Write(new byte[] { 0x05, 0xFF });
     }
     return false;
 }
开发者ID:hepper,项目名称:ProxyKit,代码行数:29,代码来源:AuthUserPass.cs


示例16: Work

        /// <summary>
        /// 获取通信返回信息
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static void Work(string cmd, NetworkStream stream)
        {
            Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(cmd);
            stream.Write(buffer, 0, buffer.Length);

            Console.WriteLine("发送信息:" +cmd);

            buffer = new Byte[1024];
            StringBuilder sb = new StringBuilder();
            Int32 numberOfBytesRead = 0;
            do
            {
                numberOfBytesRead = stream.Read(buffer, 0, buffer.Length);
                sb.Append(System.Text.Encoding.GetEncoding("GB2312").GetString(buffer, 0, numberOfBytesRead));
            }
            while (stream.DataAvailable);

            string result = sb.ToString();
            if (string.IsNullOrEmpty(result))
             Console.WriteLine("DServer无响应,请检查服务是否正常运行.");

            if (result.StartsWith("OK"))
            {
                if (result.Length == 2)
                {
                    Console.WriteLine("任务已接收");
                }
                else
                {
                    Console.WriteLine(result.Substring(3));
                }

            }
        }
开发者ID:Angliy,项目名称:DemoForTest,代码行数:40,代码来源:Program.cs


示例17: Send

        //Méthode statique pour l'envoi et la réception
        public void Send(Paquet paquet, NetworkStream stream)
        {
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, paquet);
            stream.Flush();
        }
开发者ID:Cs2iLeSwag,项目名称:Projet-Hermes,代码行数:8,代码来源:TypePaquet.cs


示例18: Write

        public void Write(NetworkStream stream)
        {
            stream.WriteByte((byte)this.Type);
            StreamHelper.WriteString(stream, this.Username);

            stream.Flush();
        }
开发者ID:tgrochowicz,项目名称:mcsharpbot,代码行数:7,代码来源:Handshake.cs


示例19: 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


示例20: 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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Sockets.OverlappedAsyncResult类代码示例发布时间:2022-05-26
下一篇:
C# Sockets.MulticastOption类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap