Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
NetworkStream is a class in the .NET Framework that provides the underlying stream of data for network access. It is specifically used in conjunction with the TcpClient and TcpListener classes to send and receive data over a network. This is applicable in the Windows environment, particularly for developers working with network applications using C# or other .NET languages. Below, we will explore how to use NetworkStream in a Windows application.
Examples:
Creating a Simple TCP Client and Server using NetworkStream
Server Code (C#):
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpServer
{
static void Main()
{
TcpListener server = null;
try
{
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
Client Code (C#):
using System;
using System.Net.Sockets;
using System.Text;
class TcpClientExample
{
static void Main()
{
try
{
Int32 port = 13000;
TcpClient client = new TcpClient("127.0.0.1", port);
Byte[] data = Encoding.ASCII.GetBytes("Hello, Server!");
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", "Hello, Server!");
data = new Byte[256];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
Executing the Application via CMD:
To run the above C# applications, you need to compile them using the .NET CLI or Visual Studio. Once compiled, you can execute the applications from the Command Prompt.
TcpServer.exe
TcpClientExample.exe
This setup will demonstrate a simple client-server communication using NetworkStream.