210 likes | 434 Views
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
E N D
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 • System.Net.NetworkInformation .net .net
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 .net .net
System.Net Dns Class //Provides simple domain name resolution functionality IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); // Also have async method: BeginGetHostAddresses .net .net
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. .net .net
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(); .net .net
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) {} } } } .net .net
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. .net .net
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() .net .net
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) {}}} .net .net
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. .net .net
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. .net .net
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(); } } .net .net
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#. .net .net
Class UdpClient //Constructors public UdpClient () public UdpClient(int Port); // Methods public Connect(IPAddress); public BeginReceive(); public EndReceive(); void BeginSend(); void EndSend(); void Connect(); .net .net
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. .net .net
UDPEchoClient.cs using System.Net.Sockets; using System.Net; classProgram { staticvoid Main(string[] args) { String message = "test"; UdpClient client = newUdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, "127.0.0.1", 5050); IPEndPoint RemoteIpEndPoint = newIPEndPoint(IPAddress.Any, 0); byte[] echo = client.Receive(ref RemoteIpEndPoint); Console.WriteLine("Received: " +Encoding.ASCII.GetString(echo)); client.Close(); Console.ReadKey(); } } .net .net
UDPEchoServer.cs using System.Net.Sockets; using System.Net; classProgram { staticvoid Main(string[] args) { UdpClient client = newUdpClient(5050); IPEndPoint RemoteIpEndPoint = newIPEndPoint(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); } } } } .net .net
What if we never get data? classProgram { publicstaticbool gotMessage = false; publicstaticbool timeout = false; staticvoid Main(string[] args) { Program pgm = newProgram(); pgm.run(); } publicvoid run() { String message = "test"; UdpClient client = newUdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, "127.0.0.1", 5050); IPEndPoint RemoteIpEndPoint = newIPEndPoint(IPAddress.Any, 0); UdpState state = newUdpState(); state.cl = client; state.re = RemoteIpEndPoint; try { client.BeginReceive(ReceiveCallback, state); Timer timer = newTimer(TimerCallback); timer.Change(5000, Timeout.Infinite); while (!gotMessage && !timeout) { Thread.Sleep(100); if (timeout) { thrownewSocketException(10060); } } } catch (SocketException ex) { Console.WriteLine("There was an error communicating with the server."); } Console.ReadKey(); } .net .net
What if we never get data? publicvoid TimerCallback(object state) { timeout = true; } publicvoid 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)); } } .net .net
Using Raw Sockets • 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 .net .net
Echo Client using sockets publicvoid run() { String message = "test"; Socket client = newSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint server = newIPEndPoint(IPAddress.Parse("127.0.0.1"), 5050); client.ReceiveTimeout = 5000; Console.WriteLine("Sending: " + message); client.SendTo(Encoding.ASCII.GetBytes(message), server); IPEndPoint RemoteIpEndPoint = newIPEndPoint(IPAddress.Any, 0); EndPoint remoteServer = (EndPoint)RemoteIpEndPoint; byte[] data = newbyte[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(); } } .net .net