Advanced .NET Programming I 15th Lecture

Slides:



Advertisements
Similar presentations
2: Application Layer 1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
Advertisements

1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
Network Programming and Java Sockets 1 Dr. Christian Vecchiola Postdoctoral Research Fellow Cloud Computing and Distributed Systems.
Process-to-Process Delivery:
Internet Protocols & Client Server Programming
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Network Layer Programing Connection-Oriented Sockets SWE 344 Internet Protocols & Client Server Programming.
Human-Computer Interface Course 5. ISPs and Internet connection.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Lesson №12 Telecommunication network software design for HTTP and Internet Lector: Aliev H.U. TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES THE DEPARTMENT.
Lector: Aliyev H.U. Lecture №6 Design of client-server communication software. TCP-based network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
Windows Programming Using C# Internet Programming.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
Network Programming and Sockets CPSC 363 Computer Networks Ellen Walker Hiram College (Includes figures from Computer Networking by Kurose & Ross, © Addison.
Özgür Zeytinci Network Programming Microsoft.NET.
Distributed Systems Concepts and Design Chapter 4.
Lector: Aliyev H.U. Lecture №11: FTP based file communication software design. Communicating with File Servers TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
Lector: Aliyev H.U. Lecture №4 Telecommunication network software design with.NET. Using sockets for network programming TASHKENT UNIVERSITY OF INFORMATION.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
Connectionless Sockets SWE 344 Internet Protocols & Client Server Programming.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Network Programming Chapter 5: Raw Socket Programming.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
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.
1 Tips & Tricks: Using System.Net To Write Better Connected Applications Durgaprasad Gorti COML02 Test Lead Microsoft Corporation.
19 – 21 MARCH 2006 Riyadh, Saudi Arabia. Internet communication with Indy Olaf Monien IT Consultant.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
UNIT - III WEB SERVICES BUILDING BLOCKS. Transport protocols for web services Transport such as HTTP and TCP are becoming common for SOAP traffic. However.
Java Networking I IS Outline  Quiz #3  Network architecture  Protocols  Sockets  Server Sockets  Multi-threaded Servers.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
1 Network Communications A Brief Introduction. 2 Network Communications.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek
The Mechanics of HTTP Requests and Responses and network connections.
Echo Networking COMP
Transport Protocols Relates to Lab 5. An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
Computing with C# and the .NET Framework
Some bits on how it works
Working at a Small-to-Medium Business or ISP – Chapter 7
Working at a Small-to-Medium Business or ISP – Chapter 7
Transport Protocols Relates to Lab 5. An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
Transport Protocols Relates to Lab 5. An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
Working at a Small-to-Medium Business or ISP – Chapter 7
Chapter 2: outline 2.1 principles of network applications
Socket programming - Java
Process-to-Process Delivery:
IS 4506 Server Configuration (HTTP Server)
Transport Protocols An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
Internet Applications and Network Programming
.Net Sockets.
Socket Programming 2: Application Layer.
Visual Programming COMP-315
Chapter 2: Application layer
Process-to-Process Delivery: UDP, TCP
Computer Networks Protocols
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
C# Language & .NET Platform 9th Lecture
Transport Protocols Relates to Lab 5. An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
CS18000: Problem Solving and Object-Oriented Programming
C# Language & .NET Platform 12th Lecture
Exceptions and networking
IS 4506 Configuring the FTP Service
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

Advanced .NET Programming I 15th 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)

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

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);

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());

Sockets client sends request to the server server handles request and 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)

Sockets in .NET (1) Server Create socket and bind it to end point Open socket for maximal 10 clients Client Create socket und end point for client 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); Socket s2 = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); IPAddress ip = IPAddress.Parse(…); 5000 … s0 Server s2 Client

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

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 }

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

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) { ... } }

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

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(); …

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

Classes WebRequest and WebResponse 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 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(); … } 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

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

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);

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); … }

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);

Sending E-mails Application.cs: Application.exe.config: 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: <configuration> <system.net> <mailSettings> <smtp deliveryMethod="network"> <network host="smtp1.ms.mff.cuni.cz"/> </smtp> </mailSettings> </system.net> </configuration>