Presentation is loading. Please wait.

Presentation is loading. Please wait.

12/5/2015.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.

Similar presentations


Presentation on theme: "12/5/2015.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."— Presentation transcript:

1 12/5/2015.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

2 12/5/2015.net 2 System.net.sockets Classes Ipv6MulticastOption LingerOption MulticastOption NetworkStream SendPacketsElement Socket – Implenets a berkley sockets interface SocketAsyncEventArgs – an aync sockets operation SocketException TcpClient – Implements a TCP Service TcpListenter UdpClient – Implement a UDP Service

3 12/5/2015.net 3 System.Net Dns Class //Provides simple domain name resolution functionality IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); // Also have async method: BeginGetHostAddresses

4 12/5/2015.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 needs to do is to establish a TCP connection on port 13 of a remote host. A TCP style connection is made using the Socket class.

5 12/5/2015.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();

6 12/5/2015.net 6 DayTimeClient.cs using 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) {} }

7 12/5/2015.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.

8 12/5/2015.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()

9 12/5/2015.net 9 DayTimeServer using 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) {}}}

10 12/5/2015.net 10 DayTimeServer in Action The 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.

11 12/5/2015.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.

12 12/5/2015.net 12 Async DateTime using 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(); }

13 12/5/2015.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#.

14 12/5/2015.net 14 Class UdpClient //Constructors public UdpClient () public UdpClient(int Port); // Methods public Connect(IPAddress); public BeginReceive(); public EndReceive(); void BeginSend(); void EndSend(); void Connect();

15 12/5/2015.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.

16 12/5/2015.net 16 UDPEchoClient.cs using 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(); }

17 12/5/2015.net 17 UDPEchoServer.cs using 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); }

18 What if we never get data? 12/5/2015.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(); }

19 What if we never get data? 12/5/2015.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)); }

20 Using Raw Sockets 12/5/2015.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

21 Echo Client using sockets 12/5/2015.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(); }


Download ppt "12/5/2015.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."

Similar presentations


Ads by Google