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


C# NetworkStream.Read方法代码示例

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


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

示例1: ServerMessage

        public ServerMessage(NetworkStream clientStream, byte[] buffer, ref int bytesRead)
        {
            //blocks until a client sends a message
            bytesRead = clientStream.Read(buffer, 0, ServerMessage.headerSize);
            if (bytesRead < ServerMessage.headerSize)
            {
                bytesRead = 0;
                return;
            }

            IntPtr ptr = Marshal.AllocHGlobal(bytesRead);
            Marshal.Copy(buffer, 0, ptr, ServerMessage.headerSize);
            header = (MessageHeader)Marshal.PtrToStructure(ptr, header.GetType());
            Marshal.FreeHGlobal(ptr);

            //Utils.Log("Client " + client.account.email + " got a packet with opcode "+msg.header.opcode, 2);

            if (header.size > 0)
            {
                byte[] databuffer = null;
                databuffer = new byte[header.size + 1];
                bytesRead = clientStream.Read(databuffer, 0, header.size);
                if (bytesRead < header.size)
                {
                    bytesRead = 0;
                }

                size = buffer.Length;
                target = new MemoryStream(buffer, 0, buffer.Length, false, true);
                reader = new BinaryReader(target, Encoding.ASCII);
            }
        }
开发者ID:Relfos,项目名称:MinimonServer,代码行数:32,代码来源:ServerMessage.cs

示例2: GameData

        /// <summary>
        /// 初始化实例并开启侦测
        /// </summary>
        /// <param name="inputClient"></param>
        /// <param name="replay"></param>
        public GameData(ref TcpClient inputClient, Action<string, byte[]> replay)
        {
            client = inputClient;
            stream = inputClient.GetStream();
            ReplyNewMessage = new Action<string, byte[]>(replay);
            stopReadFlag = false;

            Task.Run(() =>
            {

                while (true) {
                    if (stopReadFlag == true) { break; }

                    //读取数据长度
                    byte[] buffer = new byte[4];
                    stream.Read(buffer, 0, 4);

                    int length = BitConverter.ToInt32(buffer, 0);

                    //读取正文
                    buffer = new byte[length];
                    stream.Read(buffer, 0, length);

                    string head;
                    byte[] contant;

                    BallanceOnline.CombineAndSplitSign.Split(buffer, out head, out contant);

                    //调用委托处理
                    ReplyNewMessage(head, contant);
                }

            });
        }
开发者ID:yyc12345,项目名称:BallanceToolsBox,代码行数:39,代码来源:GameData.cs

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

示例4: getFile

        static void getFile(NetworkStream ns)
        {
            UInt64 fLen;
            int readBytes = 0;
            byte[] message = new byte[8];
            FileStream fs;

            try
            {
                fs = new FileStream("Config.xml", FileMode.Create, FileAccess.Write);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            readBytes = ns.Read(message, 0, 8);
            fLen = BitConverter.ToUInt64(message,0);
            message = new byte[4096];

            do
            {
                readBytes = ns.Read(message, 0, 4096);
                fs.Write(message, 0, readBytes);
                fLen -= Convert.ToUInt64(readBytes);
            } while (fLen > 0);
            fs.Close();
        }
开发者ID:ambasta,项目名称:doe,代码行数:29,代码来源:mediate.cs

示例5: Connect

        public static bool Connect(string ip, int port, string pass)
        {
            Console.WriteLine("Attempting to connect to RCON for announcements.");

            try
            {
                tcp = new TcpClient();
                tcp.Connect(ip, port);
                stream = tcp.GetStream();
                byte[] array = new byte[1024];
                int count = stream.Read(array, 0, array.Length);
                string @string = Encoding.ASCII.GetString(array, 0, count);
                if (@string.Substring(0, 4) != "v001")
                {
                    Failed(string.Concat(new string[]
                    {
                        "Server is running a newer protocol (",
                        @string.Substring(0, 4),
                        ").",
                        Environment.NewLine,
                        "You need to download a new version of RxCommand."
                    }));
                }
                else
                {
                    gameVersion = @string.Substring(4);
                    gameVersion.Trim();
                    WriteLine('a' + pass);
                    count = stream.Read(array, 0, array.Length);
                    @string = Encoding.ASCII.GetString(array, 0, count);
                    if (@string.Substring(0, 1) != "a")
                    {
                        Failed(@string.Substring(1));
                    }
                    else
                    {
                        receiver = new Thread(new ThreadStart(ReceiveLoop));
                        receiver.Start();
                        while (!receiver.IsAlive)
                        {

                        }

                        Console.WriteLine("Successfully connected to RCON.");

                        return true;
                    }
                }
            }
            catch (SocketException)
            {
                Failed("Could not connect to server.");
                tcp = null;
            }

            return false;
        }
开发者ID:JaTochNietDan,项目名称:Renegade-X-Stats-Tracker,代码行数:57,代码来源:RCON.cs

示例6: ReadStreamIntoString

 public static string ReadStreamIntoString(NetworkStream ns)
 {
     byte[] buffer = new byte[1024];
     ns.Read(buffer, 0, buffer.Length);
     while (ns.DataAvailable)
     {
         ns.Read(buffer, 0, buffer.Length);
     }
     ASCIIEncoding enc = new ASCIIEncoding();
     return enc.GetString(buffer);
 }
开发者ID:BenHall,项目名称:FootReST,代码行数:11,代码来源:NetworkStreamHandler.cs

示例7: Recieve

        /// <summary>
        /// Receieves a single object over the specified stream
        /// </summary>
        /// <param name="stream">Stream to receive the message from</param>
        /// <returns>Object received</returns>
        public static object Recieve(NetworkStream stream)
        {
            int dataLength;
            byte[] data = new byte[sizeof(Int32)];

            int bytesRead = 0;
            int totalBytesRead = 0;

            try {
                // Read the length integer
                do {
                    bytesRead = stream.Read(data, totalBytesRead, (data.Length - totalBytesRead));
                    totalBytesRead += bytesRead;
                } while (totalBytesRead < sizeof(Int32) && bytesRead != 0);

                if (totalBytesRead < sizeof(Int32)) {
                    if (totalBytesRead != 0) Console.Error.WriteLine("Message Recieve Failed: connection closed unexpectedly");
                    return null;
                }

                if (BitConverter.IsLittleEndian) Array.Reverse(data);
                dataLength = BitConverter.ToInt32(data, 0);

                if (dataLength == 0) {
                    // A test message was sent.
                    return "Test";
                } else {
                    data = new byte[dataLength];

                    // Read data until the client disconnects
                    totalBytesRead = 0;
                    do {
                        bytesRead = stream.Read(data, totalBytesRead, (dataLength - totalBytesRead));
                        totalBytesRead += bytesRead;
                    } while (totalBytesRead < dataLength && bytesRead != 0);

                    if (totalBytesRead < dataLength) {
                        Console.Error.WriteLine("Message Receive Failed: connection closed unexpectedly");
                        return null;
                    }

                    return Unpack(data);
                }
            } catch (Exception e) {
                Console.Error.WriteLine("A socket error has occured: " + e.ToString());
                return null;
            }
        }
开发者ID:Zwolf11,项目名称:BlottoBeats,代码行数:53,代码来源:Message.cs

示例8: getMessage

        private void getMessage()

        {

            while (true)

            {

                serverStream = clientSocket.GetStream();

                int buffSize = 0;

                byte[] inStream = new byte[10025];

                buffSize = clientSocket.ReceiveBufferSize;

                serverStream.Read(inStream, 0, buffSize);

                string returndata = System.Text.Encoding.ASCII.GetString(inStream);

                readData = "" + returndata;

                msg();

            }

        }
开发者ID:Mortion,项目名称:Uses,代码行数:27,代码来源:Form1.cs

示例9: ReadBytesBlocking

        //I needed a blocking read for the video because I realized it was causing major issues if the
        //Video was not fully recived into our buffer when this function was called.
        //Read would return without reading the whole file
        //This function will not return until it reads the specified number of bytes
        //Or a timeout with a default of 1 second is reached without reading anything
        public static byte[] ReadBytesBlocking(NetworkStream networkStream, int length = 256, int TimeoutMS = 1000)
        {
            byte[] bytes = new byte[length];
            int numBytesRead = 0;
            int lastBytesRead;
            System.Diagnostics.Stopwatch t = System.Diagnostics.Stopwatch.StartNew();

            while (numBytesRead < length)
            {
                int i = networkStream.Read(bytes, numBytesRead, length - numBytesRead);
                lastBytesRead = numBytesRead;
                numBytesRead += i;
                if (lastBytesRead != numBytesRead) // if data was recieved
                {
                    t.Restart();// reset timeout
                }
                else
                {
                    System.Threading.Thread.Sleep(100); // wait for data.
                }
                if(t.ElapsedMilliseconds > TimeoutMS)
                {
                    byte[] Error = new byte[1];
                    Error[0] = 0;
                    return Error;
                }
            }
            return bytes;
        }
开发者ID:johnnyRose,项目名称:PiSpy,代码行数:34,代码来源:TcpStreamReader.cs

示例10: Read

        /// <summary>
        /// Accepts message from client.
        /// </summary>
        /// <param name="networkStream"></param>
        /// <returns></returns>
        public static string Read(NetworkStream networkStream, int length = 256)
        {
            byte[] bytes = new byte[length];
            int i = networkStream.Read(bytes, 0, length);
            return Encoding.ASCII.GetString(bytes, 0, i);

            //var header = new byte[4];
            //var bytesLeft = 4;
            //var offset = 0;

            //// get length of content
            //while (bytesLeft > 0)
            //{
            //    var bytesRead = networkStream.Read(header, offset, bytesLeft);
            //    offset += bytesRead;
            //    bytesLeft -= bytesRead;
            //}

            //bytesLeft = BitConverter.ToInt32(header, 0); // length of content
            //offset = 0;

            //byte[] contentBytes = new byte[bytesLeft];

            //// get the actual content
            //while (bytesLeft > 0)
            //{
            //    var bytesRead = networkStream.Read(contentBytes, offset, bytesLeft);
            //    offset += bytesRead;
            //    bytesLeft -= bytesRead;
            //}

            //return Encoding.ASCII.GetString(contentBytes); // return the content
        }
开发者ID:johnnyRose,项目名称:PiSpy,代码行数:38,代码来源:TcpStreamReader.cs

示例11: ServerConnection

 private void ServerConnection(NetworkStream stream)
 {
     int RecievedSymbols = 0;
     byte[] recieved = new byte[2048];
     byte[] to_send = new byte[2048];
     string task = "";
     while ( (RecievedSymbols = stream.Read(recieved, 0, recieved.Length)) > 0 )
     {
         task = Resize(recieved);
         task = TaskToDo(task);
         Console.WriteLine(task);
         if (task.Equals("closed -1"))
         {
             to_send = Encoding.ASCII.GetBytes(task);
             stream.Write(to_send, 0, to_send.Length);
             client.Close();
             return;
         }
         else
         {
             to_send = Encoding.ASCII.GetBytes(task);
             stream.Write(to_send, 0, to_send.Length);
         }
        Array.Clear(to_send, 0, to_send.Length);
        Array.Clear(recieved, 0, recieved.Length);
     }
 }
开发者ID:DimasBro0110,项目名称:Big_File_Processor,代码行数:27,代码来源:Program.cs

示例12: dataRecv

        protected void dataRecv(NetworkStream ns)
        {
            byte[] lengthByte = new byte[4];

            ns.Read (lengthByte, 0, lengthByte.Length);
            Length = BitConverter.ToUInt32 (lengthByte, 0);

            data = new byte[Length];
            Array.Copy (lengthByte, data, lengthByte.Length);

            // 全データ受信する
            ns.Read (data, 4, (int)(Length - 4));

            // PacketType
            PacketType = (PacketType)BitConverter.ToInt32(data, 4);
        }
开发者ID:kon0524,项目名称:Ev3Theta,代码行数:16,代码来源:PtpPacket.cs

示例13: ReadBuffer

		protected BMSByte ReadBuffer(NetworkStream stream)
		{
			int count = 0;
			while (stream.DataAvailable)
			{
				previousSize = backBuffer.Size;
				backBuffer.SetSize(backBuffer.Size + 1024);

				count += stream.Read(backBuffer.byteArr, previousSize, 1024);
				backBuffer.SetSize(previousSize + count);
			}

			int size = BitConverter.ToInt32(backBuffer.byteArr, 0);

			readBuffer.Clear();

			readBuffer.BlockCopy(backBuffer.byteArr, backBuffer.StartIndex(4), size);

			if (readBuffer.Size + 4 < backBuffer.Size)
				backBuffer.RemoveStart(size + 4);
			else
				backBuffer.Clear();

			return readBuffer;
		}
开发者ID:predominant,项目名称:Treasure_Chest,代码行数:25,代码来源:TCPProcess.cs

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

示例15: GameClient

        public GameClient(TcpClient client)
        {
            netstream = client.GetStream();

            timer = new Stopwatch();

            byte[] message = new byte[4096];
            int msgsize = 0;

            while (true)
            {
                timer.Start();
                try { msgsize = netstream.Read(message, 0, 4096); }
                catch { break; } //socket error

                if (msgsize == 0)
                {

                    break; //client disconnected
                }

                //message received
                HandlePacket(message.Take(msgsize).ToArray());
            }

            GameServer.PlayerCount--;
            GConsole.WriteStatus("User '{0}' disconnected.", this.UserID);

            client.Close();
        }
开发者ID:RudyJ,项目名称:ODK-DarkEmu,代码行数:30,代码来源:GameClient.cs


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