Classes - Univerzita Karlova v Praze

Download Report

Transcript Classes - Univerzita Karlova v Praze

Advanced .NET Programming I
8th Lecture
http://d3s.mff.cuni.cz/~jezek
Pavel Ježek
[email protected]
CHARLES UNIVERSITY IN PRAGUE
faculty of mathematics and physics
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
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);
Server
…
5000
…
s0
Client
 Create socket und end point for
client
Socket s2 = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp
);
IPAddress ip = IPAddress.Parse(…);
s2
Client
Sockets in .NET (2)
Wait for connection
 Connect
Socket s1 = s0.Accept();
Server
…
5000
…
to end point
IPEndPoint ep = new IPEndPoint(ip,5000);
s2.Connect(ep);
s0
s2
Client
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:
Client:
int port = 13000;
string server = “nenya.ms.mff.cuni.cz”
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();
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; }
• Creation of Web request with URI
• Registration of a custom WebRequest
implementation
• HTTP method type (GET or POST)
public virtual string ContentType { get; set; }
public virtual WebHeaderCollection Headers { get; set; }
• Mime type
• Headers
public virtual Stream GetRequestStream();
public virtual WebResponse GetResponse();
…
• 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; }
• Mime Type
• Headers
public virtual Uri ResponseUri { get; }
• URI of response
public virtual Stream GetResponseStream();
…
}
• Length 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://
http://, https://
ftp://
FileWebRequest/FileWebResponse (not in ECMA standard)
HttpWebRequest/HttpWebResponse
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:
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("[email protected]", "Pavel Ježek", Encoding.UTF8),
new MailAddress("[email protected]", "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()
Application.exe.config:
);
mail.BodyEncoding = Encoding.UTF8;
<configuration>
mail.Subject = "Důležitá informace ohledně času";
mail.SubjectEncoding = Encoding.UTF8;
<system.net>
mail.Attachments.Add(new Attachment("Picture.png"));
<mailSettings>
smtpClient.Send(mail);
<smtp deliveryMethod="network">
}
<network host="smtp1.ms.mff.cuni.cz"/>
}
</smtp>
</mailSettings>
</system.net>
</configuration>