Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek

Similar presentations


Presentation on theme: "CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek"— Presentation transcript:

1 CHARLES UNIVERSITY IN PRAGUE http://d3s.mff.cuni.cz/~jezek faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek pavel.jezek@d3s.mff.cuni.cz Some of the slides are based on University of Linz.NET presentations. © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License (http://www.msdnaa.net/curriculum/license_curriculum.aspx)

2 Network Communication Namespace System.Net supports the implementation of typical client/server applications System.Net offers implementation of: Internet protocols, e.g.: TCP, UDP, HTTP; Internet services, e.g.: DNS (Domain Name System) other protocols, e.g.: IrDA System.Net.Sockets offers support for the creation of data streams over networks

3 Adressing Addressing is done by classes IPAddress: represents IP address IPEndPoint: represents end point with IP address and port Example: IPAddress ipAdr = new IPAddress("254.10.120.3"); // Create a new IPEndPoint with port number 80 (HTTP) IPEndPoint ep = new IPEndPoint(ipAdr, 80);

4 DNS (Domain Name System) DNS offers an IP into domain name mapping service Class Dns supports DNS mapping Class IPHostEntry is container class for address information Example: // Get all the addresses of a given DNS name IPHostEntry host = Dns.Resolve("dotnet.jku.at“); foreach (IPAddress ip in host.AddressList) Console.WriteLine(ip.ToString());

5 Sockets Sockets represent bidirectional communication channels, which allow sending and receiving of streamed data Client/server architectures client sends request to the server server handles request and sends back response Addressing by IP addresses and ports Data exchange by streams (see Streaming)

6 Sockets in.NET (1) Server Create socket and bind it to end point Open socket for maximal 10 clients Socket s0 = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); IPAddress ip = IPAddress.parse(…); IPEndPoint ep = new IPEndPoint(ip,5000); s0.Bind(ep); s0.Listen(10); Client Create socket und end point for client Socket s2 = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); IPAddress ip = IPAddress.Parse(…); 5000 … … s0 Server s2 Client

7 Sockets in.NET (2) Wait for connection Socket s1 = s0.Accept(); Connect to end point IPEndPoint ep = new IPEndPoint(ip,5000); s2.Connect(ep); s2 Client 5000 … … s0 Server s1 Communicate with client and disconnect s1.Receive(msg1);... s1.Send(msg2); s1.Shutdown(SocketShutdown.Both); s1.Close(); Communicate with server and disconnect s2.Send(msg1);... s2.Receive(msg2); s2.Shutdown(SocketShutdown.Both); s2.Close();

8 Example EchoServer class EchoServer { socket s; public bool StartUp(IPAddress ip, int port) { try { s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(new IPEndPoint(ip, port)); s.Listen(10); // maximal 10 clients in queue } catch (Exception e) {... } for(;;) { Communicate(s.Accept()); // waits for connecting clients }

9 Example EchoServer class EchoServer {... // returns all the received data back to the client public void Communicate(Socket clSock) { try { byte[] buffer = new byte[1024]; while (clSock.Receive(buffer) > 0) // receive data clSock.Send(buffer); // send back the data clSock.Shutdown(SocketShutdown.Both); // close sockets clSock.Close(); } catch (Exception e) {... } } public static void Main() { EchoServer = new EchoServer(); server.StartUp(IPAddress.Loopback, 5000); // start the echo server }

10 Example EchoServer class EchoClient {... public static void Main() { try { // connect to the server Socket s = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(new IPEndPoint(IPAddress.Loopback, 5000)); s.Send( Encoding.ASCII.GetBytes("This is a test“)); // send the message byte[] echo = new byte[1024]; s.Receive(echo); // receive the echo message Console.WriteLine(Encoding.ASCII.GetString(echo)); } catch (Exception e) {... } }

11 NetworkStream Socket provides interface for transmitting byte or byte arrays Class NetworkStream provides stream for reading and writing Reader and Writer can be used to read and write complex data structures

12 TcpClient/TcpListener UdpClient If you are writing a relatively simple client and do not require maximum performance, consider using TcpClient/TcpListener and UdpClient Server: int port = 13000; TcpListener server = new TcpListener(port); server.Start(); while(true) { Console.Write("Waiting for a connection... "); TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); … Client: string server = “nenya.ms.mff.cuni.cz” int port = 13000; TcpClient client = new TcpClient(server, port); NetworkStream stream = client.GetStream(); …

13 WebRequest and WebResponse For getting web resources via standard protocols (HTTP, FTP, …) Abstract classes WebRequest and WebResponse in System.Net namespace

14 Classes WebRequest and WebResponse public abstract class WebRequest { public static WebRequest Create(string uri); public static bool RegisterPrefix(string prefix, IWebRequestCreate creator ); public virtual string Method { get; set; } public virtual string ContentType { get; set; } public virtual WebHeaderCollection Headers { get; set; } public virtual Stream GetRequestStream(); public virtual WebResponse GetResponse(); … } Creation of Web request with URI Registration of a custom WebRequest implementation HTTP method type (GET or POST) Mime type Headers Stream for writing the request Response object public abstract class WebResponse { public virtual long ContentLength { get; set; } public virtual string ContentType { get; set; } public virtual WebHeaderCollection Headers { get; set; } public virtual Uri ResponseUri { get; } public virtual Stream GetResponseStream(); … } Length of response Mime Type Headers URI of response Stream for reading the response

15 WebRequest/WebResponse Subclasses WebRequest/WebResponse.Create method creates new instance of one its subclasses depending on the URI: file://FileWebRequest/FileWebResponse (not in ECMA standard) http://, https://HttpWebRequest/HttpWebResponse ftp://FtpWebRequest/FtpWebResponse (only in 2.0) Other URI prefixes can be registered to custom WebRequest/WebResponse implementations via WebRequest.RegisterPrefix method

16 Example: WebRequest and WebResponse WebRequest req = WebRequest.Create("http://d3s.mff.cuni.cz/~jezek"); if (req is HttpWebRequest) { ((HttpWebRequest) req).UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)"; ((HttpWebRequest) req).Credentials = new NetworkCredential("username", "password"); } try { using (WebResponse resp = req.GetResponse()) { foreach (string Key in resp.Headers.Keys) { Console.WriteLine("Header {0}: {1}", Key, resp.Headers[Key]); } using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { string Line; while ((Line = sr.ReadLine()) != null) { Console.WriteLine("\t{0}", Line); } } catch (WebException ex) { Console.WriteLine(ex.Message); Console.WriteLine("URI: {0}", ex.Response.ResponseUri.ToString()); if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response is HttpWebResponse) { Console.WriteLine("Status code: {0}", ((HttpWebResponse) ex.Response).StatusCode); }

17 WebClient public sealed class WebClient : Component { public WebClient(); public WebHeaderCollection Headers {get; set;} public ICredentials Credentials {get; set;} public string BaseAddress {get; set;} public WebHeaderCollection ResponseHeaders {get;} public byte[] DownloadData(string address); public void DownloadFile(string address, string fileName); public byte[] UploadData(string address, string method, byte[] data); public byte[] UploadFile(string address, string method, string fileName); public byte[] UploadValues(string address, string method, NameValueCollection data); public Stream OpenRead(string address); public Stream OpenWrite(string address, string method); … }

18 Example: WebClient using System.Net; using System.Collections.Specialized; … WebClient wc = new WebClient(); wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)"); NameValueCollection formValues = new NameValueCollection(); formValues.Add("p", "mbench"); byte[] respBytes = wc.UploadValues("http://nenya.ms.mff.cuni.cz/related.phtml", "POST", formValues); Console.WriteLine("Response headers:"); foreach (string Key in wc.ResponseHeaders.Keys) { Console.WriteLine("\t{0}: {1}", Key, wc.ResponseHeaders.Get(Key)); } Console.WriteLine("Response:"); using (StreamReader sr = new StreamReader(new MemoryStream(respBytes), Encoding.ASCII)) { string Line; while ((Line = sr.ReadLine()) != null) { Console.WriteLine("\t{0}", Line); }

19 Sending E-mails Application.cs: using System; using System.Text; using System.Net.Mail; class Program { static void Main(string[] args) { // SmtpClient smtpClient = new SmtpClient("smtp1.ms.mff.cuni.cz"); SmtpClient smtpClient = new SmtpClient(); MailMessage mail = new MailMessage( new MailAddress("pavel.jezek@mff.cuni.cz", "Pavel Ježek", Encoding.UTF8), new MailAddress("jiri.adamek@dsrg.mff.cuni.cz", "Jiří Adámek", Encoding.UTF8) ); mail.Body = String.Format( @" Ahoj Jiří, je právě {0} hodin. Pěkný den přeje, Pavel ", DateTime.Now.ToShortTimeString() ); mail.BodyEncoding = Encoding.UTF8; mail.Subject = "Důležitá informace ohledně času"; mail.SubjectEncoding = Encoding.UTF8; mail.Attachments.Add(new Attachment("Picture.png")); smtpClient.Send(mail); } Application.exe.config:


Download ppt "CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek"

Similar presentations


Ads by Google