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


C# NetworkStream类代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
开发者ID:zesus19,项目名称:c5.v1,代码行数:60,代码来源:Program.cs

示例2: NetworkStreamConnection

		public void NetworkStreamConnection ()
		{
			IPEndPoint ipe = new IPEndPoint(Dns.GetHostEntry ("www.google.com").AddressList [0], 80);
			Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			s.Close ();
			NetworkStream ns = new NetworkStream (s);
		}
开发者ID:Profit0004,项目名称:mono,代码行数:7,代码来源:NetworkStreamTest.cs

示例3: PostStream

	static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
	{
		Uri uri = new Uri (url);
		string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
		post += "Content-Type: application/x-www-form-urlencoded\r\n";
		post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
		post += "Host: " + uri.Host + "\r\n\r\n";
		post += "TEST=";
		byte[] bytes = Encoding.Default.GetBytes (post);

		IPHostEntry host = Dns.Resolve (uri.Host);
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		ssl.Write (bytes, 0, bytes.Length);
		ssl.Write (buffer, 0, buffer.Length);
		ssl.Flush ();

		StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
		string result = reader.ReadToEnd ();
		int start = result.IndexOf ("\r\n\r\n") + 4;
		start = result.IndexOf ("\r\n\r\n") + 4;
		return result.Substring (start);
	}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:28,代码来源:postecho.cs

示例4: SendCommand

        void SendCommand(NetworkStream stream, byte command, byte[] host, int port)
        {
            byte[] request = new byte[9];
            request[0] = Version;
            request[1] = command;
            request[2] = (byte)(port / 256);
            request[3] = (byte)(port % 256);
            host.CopyTo(request, 4);
            request[8] = 0;
            stream.Write(request, 0, request.Length);

            byte[] response = new byte[8];
            stream.Read(response, 0, response.Length);
            // check null byte
            if (response[0] != 0)
                throw new Socks4Exception("Server response: invalid null byte");
            switch (response[1])
            {
                case Reply.RequestGranted:
                    return;
                case Reply.RequestRejectedOrFailed:
                    throw new Socks4Exception("Server response: request rejected or failed");
                case Reply.ClientNotIdent:
                    throw new Socks4Exception("Server response: request failed because client is not running identd (or not reachable from the server)");
                case Reply.ClientIdentUserIDFailed:
                    throw new Socks4Exception("request failed because client's identd could not confirm the user ID string in the request");
                default:
                    throw new Socks4Exception("Server response: unknown reply");
            }
        }
开发者ID:Zergatul,项目名称:ZergatulLib,代码行数:30,代码来源:Socks4.cs

示例5: certConnectReply

 public void certConnectReply(byte[] packet, NetworkStream client)
 {
     // Just send the viewData
     byte[] response = { 0x04, 0x00, 0x00, 0x00, 0x00 };
     byte[] encryptedResponse = marginEncr.encrypt(response);
     sendTCPVariableLenPacket(encryptedResponse, client);
 }
开发者ID:hdneo,项目名称:mxo-hd,代码行数:7,代码来源:MarginClient.cs

示例6: Main

 public static void Main()
 {
     TcpListener tcpListener = new TcpListener(10);
     tcpListener.Start();
     Socket socketForClient = tcpListener.AcceptSocket();
     if (socketForClient.Connected)
     {
         Console.WriteLine("Client connected");
         NetworkStream networkStream = new NetworkStream(socketForClient);
         System.IO.StreamWriter streamWriter =
         new System.IO.StreamWriter(networkStream);
         System.IO.StreamReader streamReader =
         new System.IO.StreamReader(networkStream);
         string theString = "Sending";
         streamWriter.WriteLine(theString);
         Console.WriteLine(theString);
         streamWriter.Flush();
         theString = streamReader.ReadLine();
         Console.WriteLine(theString);
         streamReader.Close();
         networkStream.Close();
         streamWriter.Close();
     }
     socketForClient.Close();
     Console.WriteLine("Exiting...");
 }
开发者ID:dbremner,项目名称:hycs,代码行数:26,代码来源:AsyIOServer.cs

示例7: TestCustomProtocol

        public void TestCustomProtocol()
        {
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);
                var writer = new StreamWriter(socketStream, Encoding.ASCII, 1024);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    writer.Write("ECHO {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
                    writer.Flush();

                    var line = reader.ReadLine();
                    Console.WriteLine("Received: " + line);
                    Assert.AreEqual(currentMessage, line);
                }
            }
        }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:34,代码来源:CustomProtocolServerTest.cs

示例8: TestBatchRequest

        public void TestBatchRequest()
        {
            using (var socket = CreateClient())
            {
                var socketStream = new NetworkStream(socket);
                using (var reader = new StreamReader(socketStream, Encoding.ASCII, true))
                using (var writer = new ConsoleWriter(socketStream, Encoding.ASCII, 1024 * 8))
                {
                    reader.ReadLine();

                    int size = 100;

                    var lines = new string[size];

                    for (var i = 0; i < size; i++)
                    {
                        var line = Guid.NewGuid().ToString();
                        lines[i] = line;
                        var request = CreateRequest(line);
                        writer.Write(request);
                    }

                    writer.Flush();

                    for (var i = 0; i < size; i++)
                    {
                        var receivedLine = reader.ReadLine();
                        Assert.AreEqual(lines[i], receivedLine);
                    }
                }
            }
        }
开发者ID:huamanhtuyen,项目名称:TagLo2,代码行数:32,代码来源:ProtocolTestBase.cs

示例9: BackupProcess

        static void BackupProcess()
        {
            Console.WriteLine("I am backup!");
            
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Start();
            Socket sock = listener.AcceptSocket();
            Stream str = new NetworkStream(sock);
            StreamReader sr = new StreamReader(str);

            string line = "-1";

            try
            {
                while (true)
                    line = sr.ReadLine();
            }
            catch(IOException)
            { 
                sr.Close();
                listener.Stop();

                PrimaryProcess(Convert.ToInt32(line) + 1);
            }
        }
开发者ID:DanglingPointer,项目名称:TTK4145,代码行数:26,代码来源:Program.cs

示例10: HandleRequest

 public void HandleRequest(Url url, NetworkStream stream)
 {
     foreach (IPlugin p in plugins)
     {
         p.handleRequest(url, stream);
     }
 }
开发者ID:karinmae,项目名称:SWE1,代码行数:7,代码来源:PluginManager.cs

示例11: Client

        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
开发者ID:Team7-SoftEng,项目名称:GateofGabethulu-launcher,代码行数:27,代码来源:Client.cs

示例12: checkConflict

        public void checkConflict()
        {
            Server_Client.Client client= new Server_Client.Client();
             this.tcpClient = client.Connect(Luu.IP, Luu.Ports);

             Entities.KhoHang kh = new Entities.KhoHang("Select");
             Entities.KhoHang[] kh1 = new Entities.KhoHang[1];
             networkStream = client.SerializeObj(this.tcpClient, "KhoHang", kh);

             kh1 = (Entities.KhoHang[])client.DeserializeHepper1(networkStream, kh1);
             if (kh1 != null)
             {
                 for (int j = 0; j < kh1.Length; j++)
                 {
                     if (kh1[j].MaKho == txtMaKho.Text)
                     {
                         MessageBox.Show("Thất bại");
                         chck = "No";
                         txtMaKho.Text = new Common.Utilities().ProcessID(txtMaKho.Text);
                         break;
                     }
                     else
                         chck = "Yes";
                 }
             }
        }
开发者ID:mrk29vn,项目名称:vna-accounting,代码行数:26,代码来源:frmSuaKhoHang.cs

示例13: Main

	static void Main (string [] args)
	{
		int i = 0;

		while (args [i].StartsWith ("-")){
			if (args [i] == "-debug")
				debug = true;
			if (args [i] == "-headers")
				headers = true;
			if (args [i] == "-header")
				header = args [++i];
			i++;
		}
		
		c = new TcpClient (args [i], Int32.Parse (args [i+1]));
		c.ReceiveTimeout = 1000;
		ns = c.GetStream ();
		
		sw = new StreamWriter (ns);
		sr = new StreamReader (ns);

		string host = args [i];
		if (args [i+1] != "80")
			host += ":" + args [i+1];
		send (String.Format ("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", args [i+2], host));

		MemoryStream ms = new MemoryStream ();
		
		try {
			byte [] buf = new byte [1024];
			int n;
			
			while ((n = ns.Read (buf, 0, 1024)) != 0){
				ms.Write (buf, 0, n);
			}
		} catch {}

		ms.Position = 0;
		sr = new StreamReader (ms);

		string s;
		
		while ((s = sr.ReadLine ()) != null){
			if (s == ""){
				if (headers)
					return;
				
				string x = sr.ReadToEnd ();
				Console.Write (x);
				break;
			}  else {
				if (debug || headers)
					Console.WriteLine (s);
				if (header != null && s.StartsWith (header)){
					Console.WriteLine (s);
					return;
				}
			}
		}
	}
开发者ID:nobled,项目名称:mono,代码行数:60,代码来源:rtest.cs

示例14: Connect

        public bool Connect()
        {
            string IP = "127.0.0.1";
            client = new TcpClient(IP, 345);
            if (client.Client.Connected)
            {
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);
                string challengeCode = sr.ReadLine();
                challengeCode = challengeCode.Substring(challengeCode.IndexOf(' ') + 1);
                string responseCode = "";
                for (int i = challengeCode.Length - 1; i >= 0; i--)
                {
                    responseCode += challengeCode[i];
                }
                sw.AutoFlush = true;
                sw.WriteLine(responseCode);
                if (sr.ReadLine() == "Challenge code accepted")
                {

                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
开发者ID:master20151121,项目名称:mmoments,代码行数:33,代码来源:Connector.cs

示例15: HandShake

        public void HandShake()
        {
            try
            {
                client = new TcpClient(server, port);

                string hello = "HELLO";

                data = System.Text.Encoding.ASCII.GetBytes(hello);

                stream = client.GetStream();
                stream.Write(data, 0, data.Length);

                int i = stream.Read(bytes, 0, bytes.Length);
                string Data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                if (Data == "HI")
                {
                    //MessageBox.Show("Підключення з сервером встановлено успішно.");
                    isConnected = true;
                    toolStripMenuItem3.Enabled = true;
                    toolStripMenuItem1.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Невдалось підключитись до сервера. Спробуйте пізніше.\n");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Невдалось підключитись до сервера. Спробуйте пізніше.\n\n" + ex.ToString());
            }
        }
开发者ID:OlexReally,项目名称:Simulation-vending-machines,代码行数:33,代码来源:Form1.cs


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