Title: Networking
1Networking
- Web services
- Also a type of networking
- HTTP
- System.Net.WebRequest
- System.Net.WebResponse
- TCP/IP
- System.Net.Sockets.Socket
- Infrared communications
- Serial communications
2Simple HTTP request/response
- WebRequest and WebResponse
- inside System.Net namespace
- abstract classes
- Cant create an instance using constructor
- Use WebRequest.Create(url)
- Return an instance of HTTPWebRequest if url
starts with http// or https// - Example
using System.Net using System.IO . . WebRequest
reqWebRequest.Create(uri) WebResponse
resreq.GetResponse()
3Sample HTTP code
- HttpGetSample
- Error handling
- WebException
- Errors returned by the server
- UriFormatException
4Accessing HTTP headers
- Properties
- Accept lt-gt HttpWebRequest.Accept
- User-Agent lt-gt HttpWebRequest.User-Agent
- Server lt-gt HttpWebResponse.Server
- System.Net.WebHeaderCollection
HttpWebRequest req (HttpWebRequest)
WebRequest.Create(uri) req.Headers.Add(User-Agen
t, dotNETCF Test Program) HttpWebResponse
res (HttpWebResponse) req.GetResponse() String
server res.Headersservers
5HTTP GET
- Send data in query string
- ?FirstNameAndyLastNameWigley
- Special characters need to be encoded
- ? -gt 3f
- / -gt 3f
- Space -gt
- .Net Compact Framework does not have utility to
do encoding and decoding
6HTTP POST
public void doPost(String url, String payload)
WebRequest req WebRequest.Create(url)
req.Method POST req.ContentType
text/plain charsetutf-8 // Encode the
data byte encodedBytes
Encoding.UTF8.GetBytes(payload)
req.ContentLength encodedBytes.Length //
write encoded data into request stream
Stream requestStream req.GetRequestStream()
requestStream.Write(encodedBytes, 0,
encodedBytes.Length) requestStream.Close()
WebResponse result req.GetResponse()
7Working with Sockets
- System.Net.Sockets
- Managed implementation of winsock for .NET
framework - TcpListener and TcpClient
- blocking synchronous transfer
- Socket class
- asynchronous transfer
- UdpClient class
8System.Net.Sockets.TcpListener
- Listen on a particular port
- TcpListener tcpServer new
TcpListener(695) - Listen on the port assigned by the system
- TcpListener tcpServer new TcpListener(0)
- tcpServer.Start()
- System.Net.IPEndPoint assignedEndpoint
(System.Net.IPEndPoint) tcpServer.LocalEndPoint - int localport assignedEndPoint.Port
- Create IPEndPoint object and pass into
TcpListener constructor - IPEndPoint endPt new
IPEndPoint(IPAddress.Parse(192.168.0.1), 695) - TcpListener tcpServer new
TcpListener(endPt)
9TcpListenerSample Example
- TcpClient offers methods to send and receive
data - TcpClient.Connect() make a connection to the
server - TcpClient.GetStream returns the IO stream
10System.Net.Sockets.UdpClient
- To send a datagram
- UdpClient udpClient new UdpClient()
- byte msgBytes
- System.Text.Encoding.ASCII.GetBytes(Message)
- udpClient.Send(msgBytes, msgBytes.Length,
- 192.168.1.101,
6950) - To receive a datagram, use udpClient.Receive()
-