1 / 36

Özgür Zeytinci

Network Programming Microsoft .NET. Özgür Zeytinci. Main Topics. .NET Overview .NET Code Development .NET Networking Namespaces .NET Socket Programming Example. .NET Overview.

tavi
Download Presentation

Özgür Zeytinci

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Network Programming Microsoft .NET Özgür Zeytinci

  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 Windows2000, 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.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 • SocketAddress : Identifies a socket address • IPAddress : Provides an Internet Protocol (IP) address • DnsPermission : Controls rights to access Domain Name System (DNS) servers on the network

  16. System.Net • Primary Classes (cnt.) • NetworkCredential : Credentials for password-based authentication schemes • HttpWebRequest, HttpWebResponse : HTTP implementation of request and response objects • 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. System.Net.Sockets • Primary Classes • 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. UDP Chat Client Multicast Group UDP Chat Client UDP Chat Client Send Msg Recieve Msg .NET Socket Programming Example

  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 voidMain() {...} public static voidInitialize() {...} public static voidListener() {...} public static voidTerminate() {...} } 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) 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(); Console.WriteLine("Starting Listener thread..."); Thread t = new Thread(new ThreadStart(Listener)); t.Start(); Byte [] buffer = null; Encoding ASCII = Encoding.ASCII; bool m_ShuttingDown = false; .... }

  22. while(!m_ShuttingDown) { (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) t.Abort(); t.Join(); Console.WriteLine("Closing connection..."); Terminate(); } // Main

  24. public static void Initialize() { (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) // 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) // 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) m_Client.DropMulticastGroup(m_GroupAddress); }

  28. Network Programming Microsoft .NET Özgür Zeytinci

  29. (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) 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) 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) 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) 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) 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) 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) 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.

More Related