Özgür Zeytinci

36
Özgür Zeytinci Network Programming Microsoft .NET

description

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

Transcript of Özgür Zeytinci

Page 1: Özgür Zeytinci

Özgür Zeytinci

Network Programming

Microsoft .NET

Page 2: Özgür Zeytinci

Main Topics

• .NET Overview• .NET Code Development• .NET Networking Namespaces• .NET Socket Programming Example

Page 3: Özgür Zeytinci

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

Page 4: Özgür Zeytinci

.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

Page 5: Özgür Zeytinci

.NET Overview

Common Language RuntimeBase Framework Classes

Data and XML Classes

XML WebServices

Web Forms Windows

FormsASP.NET

Common Language RuntimeBase Framework Classes

Data and XML Classes

XML WebServices

Web Forms Windows

FormsASP.NET

.NET Framework, the programming model of the .NET platform:

Page 6: Özgür Zeytinci

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

Page 7: Özgür Zeytinci

.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

Page 8: Özgür Zeytinci

.NET IL Disassembler

Parses the application's metadata and displays information about the application in a treelike hierarchy.

Page 9: Özgür Zeytinci

.NET vs J2EE

Page 10: Özgür Zeytinci

.NET Networking Namespaces

• System.Threading• System.Net• System.Net.Sockets• System.Runtime.RemotingSystem.Runtime.Remoting

Page 11: Özgür Zeytinci

System.Threading

• Provides classes that enable multi-threaded programming– Synchronize mutually-exclusive threads– Manage groups of threads– Enable timing

Page 12: Özgür Zeytinci

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 _

Page 13: Özgür Zeytinci

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

Page 14: Özgür Zeytinci

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

Page 15: Özgür Zeytinci

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

Page 16: Özgür Zeytinci

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

Page 17: Özgür Zeytinci

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

Page 18: Özgür Zeytinci

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

Page 19: Özgür Zeytinci

.NET Socket Programming Example

MulticastGroup

UDP Chat Client

UDP Chat Client

UDP Chat Client

Send MsgRecieve Msg

Page 20: Özgür Zeytinci

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() {...} public static void Initialize() {...} public static void Listener() {...} public static void Terminate() {...}}

using System;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.Text;

Page 21: Özgür Zeytinci

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; ....}

Page 22: Özgür Zeytinci

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

Page 23: Özgür Zeytinci

(BACK TO CLASS)

t.Abort(); t.Join();

Console.WriteLine("Closing connection...");

Terminate();

} // Main

Page 24: Özgür Zeytinci

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

}

Page 25: Özgür Zeytinci

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

Page 26: Özgür Zeytinci

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

Page 27: Özgür Zeytinci

public static void Terminate() { (BACK TO MAIN)

m_Client.DropMulticastGroup(m_GroupAddress); }

Page 28: Özgür Zeytinci

Özgür Zeytinci

Network Programming

Microsoft .NET

Page 29: Özgür Zeytinci

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

Page 30: Özgür Zeytinci

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

Page 31: Özgür Zeytinci

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

Page 32: Özgür Zeytinci

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

Page 33: Özgür Zeytinci

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

Page 34: Özgür Zeytinci

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

Page 35: Özgür Zeytinci

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

Page 36: Özgür Zeytinci

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