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

Slides:



Advertisements
Similar presentations
Lecture 2b Sockets Erick Pranata © Sekolah Tinggi Teknik Surabaya 1.
Advertisements

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.
1 Creating a network app Write programs that  run on different end systems and  communicate over a network.  e.g., Web: Web server software communicates.
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.
Client, Server, HTTP, IP Address, Domain Name. Client-Server Model Client Bob Yahoo Server yahoo.com/finance.html A text file named finance.html.
UNIX Sockets COS 461 Precept 1. Clients and Servers Client program – Running on end host – Requests service – E.g., Web browser Server program – Running.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
TP2653 Adv Web Programming SOAP and WSDL. SOAP Simple Object Access Protocol – Lightweight XML-based messaging protocol – A protocol for accessing a Web.
Process-to-Process Delivery:
2: Application Layer 1 Socket Programming TCP and UDP.
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.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
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.
UDP Client-Server. The Socket Class The Socket class provides a set of methods and properties for network communications. The Socket class allows you.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
 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,
2: Application Layer1 Socket programming Socket API Explicitly created, used, released by apps Client/server paradigm Two types of transport service via.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
CS 3830 Day 9 Introduction 1-1. Announcements r Quiz #2 this Friday r Demo prog1 and prog2 together starting this Wednesday 2: Application Layer 2.
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.
1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm r two types of.
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.
Application Layer 2-1 Chapter 2 Application Layer Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Application Layer – Lecture.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
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.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th Lecture Pavel Ježek
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.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
1 Network Communications A Brief Introduction. 2 Network Communications.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Computing with C# and the .NET Framework
Process-to-Process Delivery:
Transport Protocols An overview of the transport protocols of the TCP/IP protocol suite. Also, a short discussion of UDP.
.Net Sockets.
Visual Programming COMP-315
Chapter 2: Application layer
Process-to-Process Delivery: UDP, TCP
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Advanced .NET Programming I 15th Lecture
C# Language & .NET Platform 12th Lecture
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek 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 (

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

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

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

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) 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(" 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(" "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 s 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 "Pavel Ježek", Encoding.UTF8), new "Jiří Adámek", Encoding.UTF8) ); mail.Body = 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: