21
03/30/22 .net .net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control System.Net.Sockets System.Net.Security System.Net.Cache System.Net.NetworkInformation he system.net namespace provides etworking support in .net languages

system

Embed Size (px)

DESCRIPTION

system.net. The system.net namespace provides Networking support in .net languages. Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control System.Net.Sockets System.Net.Security System.Net.Cache - PowerPoint PPT Presentation

Citation preview

04/19/23 .net .net 1

system.net

• Contains any network functionallity you would need in c#

• Several sub namespaces exists to allow for more fined control– System.Net.Sockets

– System.Net.Security

– System.Net.Cache

– System.Net.NetworkInformation

The system.net namespace provides Networking support in .net languages

04/19/23 .net .net 2

System.net.socketsClassesIpv6MulticastOptionLingerOptionMulticastOptionNetworkStreamSendPacketsElementSocket – Implenets a berkley sockets interfaceSocketAsyncEventArgs – an aync sockets operationSocketExceptionTcpClient – Implements a TCP ServiceTcpListenterUdpClient – Implement a UDP Service

04/19/23 .net .net 3

System.Net Dns Class//Provides simple domain name resolution functionality

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

// Also have async method: BeginGetHostAddresses

04/19/23 .net .net 4

Daytime Service

Most UNIX servers run the daytime service on TCP port 13.

cobalt> telnet queeg.cs.rit.edu 13 Trying 129.21.38.145... Connected to queeg. Escape character is '^]'. Fri Feb 6 08:33:44 Connection closed by foreign host. It is easy to write a C# daytime client. All the program needsto do is to establish a TCP connection on port 13 of a remote host.

A TCP style connection is made using the Socket class.

04/19/23 .net .net 5

Sockets.TcpClient// Constructors (partial list)public TcpClient()public TcpClient(String host, Int32 port);

// Methods (partial list)public void close();public void connect(IpAddress, Int32)

public NetworkStream GetStream();

04/19/23 .net .net 6

DayTimeClient.csusing System.Net; using System.Net.Sockets;

namespace Daytime {class DayTimeClient {

static void Main(String args[]) { try {

TcpClient conn = new TcpClient(“queeg.cs.rit.edu”, 13);StreamReader reader = new StreamReader(conn.GetStream);reader.ReadLine();

} catch (exception e) {} }}}

04/19/23 .net .net 7

A C# Daytime Server

• It is easy to create a daytime server in C# (the only real problem is that your server will not be able to use port 13).

• The server version of the program will use a TcpListener to communicate with a client.

• A TcpListener will open a TCP port and wait for a connection. • Once a request is detected, a new port will be created, and the

connection will be established between the client's source port and this new port.

• Most servers listen for requests on a particular port, and then service that request on a different port.

• This makes it easy for the server to accept and service requests at the

same time.

04/19/23 .net .net 8

Class TcpListener

// Constructors (partial list)

public Tcplistener(int port);public Tcplistener((Ipaddress, int port);

// Methods (partial list)

public TcpClient AcceptTcpClient();public void Start();Public void Stop()

04/19/23 .net .net 9

DayTimeServerusing System.Net; using System.Net.Sockets; using System.IO;

class DayTimeServer { static void Main(String args[]) { try { TcpListener listener = new TcpListener(1313);

while (true) { TcpClient clientSocket = listener.AcceptTcpClient(); NetworkStream networkStream = clientSocket.GetStream(); StreamWriter streamWriter = new StreamWriter(networkStream); streamWriter.WriteLine(DateTime.Now.ToLongTimeString()); streamWriter.Flush(); clientSocket.Close();

} } catch(Exception e) {}}}

04/19/23 .net .net 10

DayTimeServer in ActionThe output from the daytime server looks like this: kiev> mono DayTimeServer.exe

The client output looks like this:

cobalt> telnet kiev 1313 Trying 129.21.38.145... Connected to kiev. Escape character is '^]'. 01:43:00pm Connection closed by foreign host.

04/19/23 .net .net 11

Multi-Threaded Servers

• It is quite easy, and natural in C#, to make a server multi-threaded.

• In a multi-threaded server a new thread is created to handle each request.

• Clearly for a server such as the daytime server this is not necessary, but for an FTP server this is almost required.

• The code for the multi-threaded version of the server consists of using a delegate to accept the incoming connections

• BeginAcceptTcpClient will start the listen asynchronously.

04/19/23 .net .net 12

Async DateTimeusing System.Net; using System.Net.Sockets; using System.IO;

private static AutoResetEvent connectionWaitHandle = new AutoResetEvent(false); static void Main(string[] args) { TcpListener listener = new TcpListener(1313); listener.Start(); while (true) { listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener); connectionWaitHandle.WaitOne(); //Wait until a client has begun handling an event } }

public static void DoAcceptTcpClientCallback(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient clientSocket = listener.EndAcceptTcpClient(ar); NetworkStream networkStream = clientSocket.GetStream(); System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream); streamWriter.WriteLine(DateTime.Now.ToLongTimeString()); streamWriter.Flush(); clientSocket.Close(); }}

04/19/23 .net .net 13

Datagrams

• Datagram packets are used to implement a connectionless, packet based, delivery service.

• Each message is routed from one machine to another based solely on information contained within that packet.

• Multiple packets sent from one machine to another might be routed differently, and might arrive in any order.

• Packets may be lost or duplicated during transit.

• The class UdpClient represents a datagram in C#.

04/19/23 .net .net 14

Class UdpClient

//Constructorspublic UdpClient ()public UdpClient(int Port);

// Methodspublic Connect(IPAddress);public BeginReceive();public EndReceive();

void BeginSend();void EndSend();void Connect();

04/19/23 .net .net 15

Echo Services

• A common network service is an echo server

• An echo server simply sends packets back to the sender

• A client creates a packet, sends it to the server, and waits for a response.

• Echo services can be used to test network connectivity and performance.

• There are typically different levels of echo services. Each provided by a different layer in the protocol stack.

04/19/23 .net .net 16

UDPEchoClient.csusing System.Net.Sockets; using System.Net;

class Program { static void Main(string[] args) { String message = "test"; UdpClient client = new UdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, "127.0.0.1", 5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] echo = client.Receive(ref RemoteIpEndPoint); Console.WriteLine("Received: " +Encoding.ASCII.GetString(echo)); client.Close(); Console.ReadKey(); }}

04/19/23 .net .net 17

UDPEchoServer.csusing System.Net.Sockets; using System.Net;

class Program { static void Main(string[] args) { UdpClient client = new UdpClient(5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { try { byte[] data = client.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(data); client.Send(data, data.Length, RemoteIpEndPoint); Console.WriteLine("Echoing: " + returnData); } catch (SocketException ex) { Console.WriteLine(ex.Message); } } } }

What if we never get data?

04/19/23 .net .net 18

class Program { public static bool gotMessage = false; public static bool timeout = false; static void Main(string[] args) { Program pgm = new Program(); pgm.run(); } public void run() { String message = "test"; UdpClient client = new UdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, "127.0.0.1", 5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpState state = new UdpState(); state.cl = client; state.re = RemoteIpEndPoint; try { client.BeginReceive(ReceiveCallback, state); Timer timer = new Timer(TimerCallback); timer.Change(5000, Timeout.Infinite); while (!gotMessage && !timeout) { Thread.Sleep(100); if (timeout) { throw new SocketException(10060); } } } catch (SocketException ex) { Console.WriteLine("There was an error communicating with the server."); } Console.ReadKey(); }

What if we never get data?

04/19/23 .net .net 19

public void TimerCallback(object state) { timeout = true; }

public void ReceiveCallback(IAsyncResult ar) { UdpClient cl = (UdpClient)((UdpState)(ar.AsyncState)).cl; IPEndPoint re = (IPEndPoint)((UdpState)(ar.AsyncState)).re; Byte[] echo = cl.EndReceive(ar, ref re); gotMessage = true; Console.WriteLine("Received: " + Encoding.ASCII.GetString(echo));

} }

Using Raw Sockets

04/19/23 .net .net 20

• The use of TcpClient and UdpClient in C# is convenient, but may not provide all the functionality we need (Timeouts for example).

• Using raw sockets are not significantly more complicated, but provide a lot more flexibility

Echo Client using sockets

04/19/23 .net .net 21

public void run() { String message = "test"; Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint server = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5050); client.ReceiveTimeout = 5000; Console.WriteLine("Sending: " + message); client.SendTo(Encoding.ASCII.GetBytes(message), server); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); EndPoint remoteServer = (EndPoint)RemoteIpEndPoint;

byte[] data = new byte[1024]; try { int recv = client.ReceiveFrom(data, ref remoteServer); Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));

} catch (SocketException) { Console.WriteLine("There was an error communicating with the server."); } Console.ReadKey(); } }