Download presentation
Presentation is loading. Please wait.
Published byLeon Copeland Modified over 9 years ago
1
Özgür Zeytinci Network Programming Microsoft.NET
2
Main Topics.NET Overview.NET Code Development.NET Networking Namespaces.NET Socket Programming Example
3
.NET Overview Aim : Individual devices and Web sites are simply connected through the Internet to one in which devices, services, and computers work together to provide richer solutions for users.
4
.NET Overview.NET spans clients, servers and services and consists of: –XML Web services and applications –a set of servers, including Windows 2000, SQL Server and BizTalk Server –client software, such as Windows XP and Windows CE –tools, such as Visual Studio.NET
5
.NET Overview.NET Framework, the programming model of the.NET platform:
6
.NET Overview The.NET infrastructure refers to all the technologies that make up the new environment : – Common Language Runtime (CLR), the virtual machine in which.NET applications function. – Base Class Library (BCL), include support for everything from file I/O and database I/O to XML and SOAP.
7
.NET Application Development You write source code in C# You compile it using the C# compiler into an EXE (MSIL - Microsoft intermediate language), and metadata is created During execution, since MSIL code cannot be executed directly, the CLR compiles the MSIL by using a just-in-time (JIT) compiler into native CPU instructions
8
.NET IL Disassembler Parses the application's metadata and displays information about the application in a treelike hierarchy.
9
.NET vs J2EE
10
.NET Networking Namespaces System.Threading System.Net System.Net.Sockets System.Runtime.RemotingSystem.Runtime.Remoting
11
System.Threading Provides classes that enable multi-threaded programming –Synchronize mutually-exclusive threads –Manage groups of threads –Enable timing
12
System.Threading Primary Classes – Monitor, Mutex : Provides the synchronization of threading objects using locks and wait/signals __ – ReaderWriterLock : Defines the lock that implements single-writer and multiple-reader semantics __ – Thread : Represents threads that execute within the runtime to create and control threads __
13
System.Threading Primary Classes – ThreadPool : Posts work items to the thread pool and queues work items for execution on the first available thread from the thread pool – Timeout : Contains timeout value for methods
14
System.Net Provides a simple programming interface to – Many of the protocols found on the network today –An implementation of network services that enables you to develop applications that use Internet resources
15
System.Net Primary Classes – Dns : Provides simple domain name resolution functionality – DnsPermission : Controls rights to access Domain Name System (DNS) servers on the network – IPAddress : Provides an Internet Protocol (IP) address – SocketAddress : Identifies a socket address
16
System.Net Primary Classes (cnt.) – HttpWebRequest, HttpWebResponse : HTTP implementation of request and response objects – NetworkCredential : Credentials for password- based authentication schemes – WebClient : Provides common methods for sending data to and receiving data from a resource identified by a URI
17
System.Net.Sockets Provides –A managed implementation of the Windows Sockets interface for developers that need to tightly control access to the network –Encapsulations for TCP and UDP clients and listeners
18
Primary Classes System.Net.Sockets – MulticastOption : Contains IP address values for IP multicast packets __ – Socket : Implements the Berkeley sockets interface __ – TCPClient, TCPListener : Provides client connections and listeners for TCP network __ – UDPClient : Provides UDP network services __
19
.NET Socket Programming Example Multicast Group UDP Chat Client UDP Chat Client UDP Chat Client Send Msg Recieve Msg
20
public class Chat { private static UdpClient m_Client; private static int ListenerPort = 8080; private static int SenderPort = 8080; private static int LocalPort, RemotePort; private static string m_szHostName; private static IPAddress m_GroupAddress; private static IPHostEntry m_LocalHost; private static IPEndPoint m_RemoteEP; private static bool m_Done = false; public static void Main() {...}Main public static void Initialize() {...}Initialize public static void Listener() {...}Listener public static void Terminate() {...}Terminate } using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text;
21
public static void Main( String [] args ) {(BACK TO CLASS)BACK TO CLASS LocalPort = SenderPort; RemotePort = ListenerPort; m_szHostName = Dns.GetHostName(); m_LocalHost = Dns.GetHostByName(m_szHostName); Console.WriteLine("Local Port: {0}, Remote: {1}", LocalPort, RemotePort); Console.WriteLine("Initializing..."); Initialize();Initialize Console.WriteLine("Starting Listener thread..."); Thread t = new Thread(new ThreadStart(Listener));Listener t.Start(); Byte [] buffer = null; Encoding ASCII = Encoding.ASCII; bool m_ShuttingDown = false;.... }
22
while(!m_ShuttingDown) {(BACK TO CLASS)BACK TO CLASS String s = Console.ReadLine(); if( s.Length == 0 ) continue; if(String.Compare(s,0,"@",0,1) == 0) { m_Done = true; // send a terminator to ourselves, receiving thread can shut down s = m_szHostName + ":@"; m_ShuttingDown = true; } else { s = m_szHostName + ":" + s; } buffer = new Byte[s.Length + 1]; // send data to remote peer int len = ASCII.GetBytes( s.ToCharArray(), 0, s.Length, buffer, 0); int ecode = m_Client.Send(buffer, len, m_RemoteEP); if(ecode <= 0) { Console.WriteLine("Error in send : " + ecode); }
23
(BACK TO CLASS)BACK TO CLASS t.Abort(); t.Join(); Console.WriteLine("Closing connection..."); Terminate();Terminate } // Main
24
public static void Initialize() { (BACK TO MAIN)BACK TO MAIN // instantiate UdpCLient m_Client = new UdpClient(LocalPort); // Create an object for Multicast Group m_GroupAddress = IPAddress.Parse("224.0.0.1"); // Join Group try { m_Client.JoinMulticastGroup(m_GroupAddress, 100); } catch(Exception) { Console.WriteLine("Unable to join multicast group"); } // Create Endpoint for peer m_RemoteEP = new IPEndPoint( m_GroupAddress, RemotePort ); }
25
public static void Listener() { (BACK TO MAIN)BACK TO MAIN // The listener waits for data to come and buffers it Thread.Sleep(2000); // make sure client2 is receiving Encoding ASCII = Encoding.ASCII; while(!m_Done) { IPEndPoint endpoint = null; Byte[] data = m_Client.Receive(ref endpoint); String strData = ASCII.GetString(data); if( strData.IndexOf(":@") > 0 ) { // we received a termination indication now we have to decide if it is // from our main thread shutting down, or from someone else Char [] separators = {':'}; String [] vars = strData.Split(separators); if( vars[0] == m_szHostName ) { // this is from ourselves, therefore we end now Console.WriteLine("shutting down Listener thread..."); m_Done = true; }
26
else { (BACK TO MAIN)BACK TO MAIN // this is from someone else Console.WriteLine("{0} has left the conversation", vars[0]); } }else { // this is normal data received from others as well as ourselves // check to see if it is from ourselves before we print if(strData.IndexOf(":") > 0) { Char [] separators = {':'}; String [] vars = strData.Split(separators); if( vars[0] != m_szHostName ) { Console.WriteLine(strData); } } // while Console.WriteLine("Listener thread finished..."); return; }
27
public static void Terminate() { (BACK TO MAIN)BACK TO MAIN m_Client.DropMulticastGroup(m_GroupAddress); }
28
Özgür Zeytinci Network Programming Microsoft.NET
29
(BACK)BACK Monitor [C#]public sealed class Monitor Monitor exposes the ability to take and release the sync block lock on an object on demand via Enter, TryEnter and Exit. Mutex [C#]public sealed class Mutex : WaitHandle Mutex is a synchronization primitive that allows exclusive access to the shared resource to only one thread. Wait can be used to request ownership of the mutex. The thread must call ReleaseMutex the same number of times to release ownership of the mutex lock.
30
(BACK)BACK ReaderWriterLock [C#]public sealed class ReaderWriterLock Use in large numbers, such as per object synchronization. Timeout. This is a valuable feature to detect deadlocks. Nested locks by readers and writers. Spin counts for avoiding context switches on multiprocessor machines.
31
(BACK)BACK Thread [C#]public sealed class Thread AllocateDataSlot Allocates an unnamed data slot on all the threads. AllocateNamedDataSlot Allocates a named data slot on all of the threads. FreeNamedDataSlot Frees a previously allocated named data slot. GetData Retrieves the value from the specified slot on the current thread, for that thread's current domain. GetDomain Returns the current domain in which the current thread is running. The get and set accessors work on the hard thread, not the logical thread. Therefore, they are package-protected and should not be available for general consumption. GetNamedDataSlot Looks up a named data slot. ResetAbort Resets an Abort. SetData Sets the data in the specified slot on the currently running thread, for that thread's current domain. Sleep Suspends the current thread for a specified time.
32
(BACK)BACK MulticastOption [C#]public class MulticastOption Sets IP address values when joining or leaving an IP multicast group. Example: [C#] Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption( groupIP ));
33
(BACK)BACK Socket [C#]public class Socket : IDisposable The Socket class creates a managed version of an Internet transport service. Primary methods: Bind, Connect, Send, SendTo, Recieve, RecieveFrom, Shutdown, Close. Example: [C#] IPAddress hostadd = Dns.Resolve(server).AddressList[0]; IPEndPoint EPhost = new IPEndPoint(hostadd, 80); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); s.Connect(EPhost); s.Send(ByteGet, ByteGet.Length, 0);
34
(BACK)BACK TCPClient [C#]public class TcpClient : Idisposable The TcpClient class builds upon the Socket class to provide TCP services at a higher level of abstraction. Example: [C#] // Connect to a TCP Server TcpClient myClient = new TcpClient("time.contoso.com",13); // Get the response stream Stream myStream = myClient.GetStream();
35
(BACK)BACK TCPListener [C#]public class TcpListener The TcpListener class builds upon the Socket class to provide TCP services at a higher level of abstraction. Example: [C#] TcpListener myListener = new TcpListener(13); myListener.Start(); // Program blocks on Accept() until a client connects. Socket mySocket = myListener.AcceptSocket();
36
(BACK)BACK UDPClient [C#]public class UdpClient : IDisposable The UdpClient class provides access to UDP services at a higher level of abstraction than the Socket class does. UdpClient connects to remote hosts and receives connections from remote clients.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.