12/5/2015.net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control –System.Net.Sockets.

Slides:



Advertisements
Similar presentations
Asynchronous Sockets SWE 344 Internet Protocols & Client Server Programming.
Advertisements

CSCI Java Networking1 Java Net Classes ClassDescription DatagramPacketThis class represents a datagram packet. DatagramSocketThis class represents.
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Umut Girit  One of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer.
SWE 344 Internet Protocols & Client Server Programming The C# Sockets Helper Classes.
2: Application Layer 1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
User Datagram Protocol. Introduction UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
MS.Net Framework with emphasis on online gaming Ed Mucker CS522 9 Dec 02.
McGraw-Hill©The McGraw-Hill Companies, Inc., 2004 Application Layer PART VI.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 Network Layers Application Transport Network Data-Link Physical bits.
Network Programming and Java Sockets 1 Dr. Christian Vecchiola Postdoctoral Research Fellow Cloud Computing and Distributed Systems.
2: Application Layer 1 Socket Programming TCP and UDP.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Network Layer Programing Connection-Oriented Sockets SWE 344 Internet Protocols & Client Server Programming.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
Lector: Aliyev H.U. Lecture №6 Design of client-server communication software. TCP-based network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
Windows Programming Using C# Internet Programming.
Lector: Aliyev H.U. Lecture №9 Broadcast network software design TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES THE DEPARTMENT OF DATA COMMUNICATION NETWORKS.
-1- Georgia State UniversitySensorweb Research Laboratory CSC4220/6220 Computer Networks Dr. WenZhan Song Associate Professor, Computer Science.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
ICOM 6115©Manuel Rodriguez-Martinez ICOM 6115 – Computer Networks and the WWW Manuel Rodriguez-Martinez, Ph.D. Lecture 26.
Socket Programming Tutorial. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Lector: Aliyev H.U. Lecture №4 Telecommunication network software design with.NET. Using sockets for network programming TASHKENT UNIVERSITY OF INFORMATION.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
UDP Client-Server. The Socket Class The Socket class provides a set of methods and properties for network communications. The Socket class allows you.
Java Socket programming. Socket programming with TCP.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.
Network Programming with C# Exceed Camp #2, CPE, KU Day 3.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
Connectionless Sockets SWE 344 Internet Protocols & Client Server Programming.
2: Application Layer1 Socket programming Socket API Explicitly created, used, released by apps Client/server paradigm Two types of transport service via.
Threads & Networking C# offers facilities for multi threading and network programming an application roughly corresponds to a process, handled by the OS.
IP multicasting SWE 344 Internet Protocols & Client Server Programming.
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 7 Application.
Socket Programming Introduction. Socket Definition A network socket is one endpoint in a two-way communication flow between two programs running over.
Advanced UNIX programming Fall 2002, lecture 16 Instructor: Ashok Srinivasan Acknowledgements: The syllabus and power point presentations are modified.
Networking OSI (Open Systems Interconnection) model of computer networking, seven layers (the Application, Presentation, Session, Transport, Network, Data.
1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm r two types of.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
1 Network Communications A Brief Introduction. 2 Network Communications.
Advance Computer Programming Networking Basics – explores the java.net package which provides support for networking. – Also Called “programming for the.
1 K. Salah Application Layer Module K. Salah Network layer duties.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Echo Networking COMP
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Client/Server Example
Multi-routing the '.Net' Gigax, Kevin Edward Torres, Francisco Javier
Socket Programming.
.Net Sockets.
Visual Programming COMP-315
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Socket Programming with UDP
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

12/5/2015.net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control –System.Net.Sockets –System.Net.Security –System.Net.Cache –System.Net.NetworkInformation The system.net namespace provides Networking support in.net languages

12/5/2015.net 2 System.net.sockets Classes Ipv6MulticastOption LingerOption MulticastOption NetworkStream SendPacketsElement Socket – Implenets a berkley sockets interface SocketAsyncEventArgs – an aync sockets operation SocketException TcpClient – Implements a TCP Service TcpListenter UdpClient – Implement a UDP Service

12/5/2015.net 3 System.Net Dns Class //Provides simple domain name resolution functionality IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); // Also have async method: BeginGetHostAddresses

12/5/2015.net 4 Daytime Service Most UNIX servers run the daytime service on TCP port 13. cobalt> telnet queeg.cs.rit.edu 13 Trying Connected to queeg. Escape character is '^]'. Fri Feb 6 08:33:44 Connection closed by foreign host. It is easy to write a C# daytime client. All the program needs to do is to establish a TCP connection on port 13 of a remote host. A TCP style connection is made using the Socket class.

12/5/2015.net 5 Sockets.TcpClient // Constructors (partial list) public TcpClient() public TcpClient(String host, Int32 port); // Methods (partial list) public void close(); public void connect(IpAddress, Int32) public NetworkStream GetStream();

12/5/2015.net 6 DayTimeClient.cs using System.Net; using System.Net.Sockets; namespace Daytime { class DayTimeClient { static void Main(String args[]) { try { TcpClient conn = new TcpClient(“queeg.cs.rit.edu”, 13); StreamReader reader = new StreamReader(conn.GetStream); reader.ReadLine(); } catch (exception e) {} }

12/5/2015.net 7 A C# Daytime Server It is easy to create a daytime server in C# (the only real problem is that your server will not be able to use port 13). The server version of the program will use a TcpListener to communicate with a client. A TcpListener will open a TCP port and wait for a connection. Once a request is detected, a new port will be created, and the connection will be established between the client's source port and this new port. Most servers listen for requests on a particular port, and then service that request on a different port. This makes it easy for the server to accept and service requests at the same time.

12/5/2015.net 8 Class TcpListener // Constructors (partial list) public Tcplistener(int port); public Tcplistener((Ipaddress, int port); // Methods (partial list) public TcpClient AcceptTcpClient(); public void Start(); Public void Stop()

12/5/2015.net 9 DayTimeServer using System.Net; using System.Net.Sockets; using System.IO; class DayTimeServer { static void Main(String args[]) { try { TcpListener listener = new TcpListener(1313); while (true) { TcpClient clientSocket = listener.AcceptTcpClient(); NetworkStream networkStream = clientSocket.GetStream(); StreamWriter streamWriter = new StreamWriter(networkStream); streamWriter.WriteLine(DateTime.Now.ToLongTimeString()); streamWriter.Flush(); clientSocket.Close(); } } catch(Exception e) {}}}

12/5/2015.net 10 DayTimeServer in Action The output from the daytime server looks like this: kiev> mono DayTimeServer.exe The client output looks like this: cobalt> telnet kiev 1313 Trying Connected to kiev. Escape character is '^]'. 01:43:00pm Connection closed by foreign host.

12/5/2015.net 11 Multi-Threaded Servers It is quite easy, and natural in C#, to make a server multi-threaded. In a multi-threaded server a new thread is created to handle each request. Clearly for a server such as the daytime server this is not necessary, but for an FTP server this is almost required. The code for the multi-threaded version of the server consists of using a delegate to accept the incoming connections BeginAcceptTcpClient will start the listen asynchronously.

12/5/2015.net 12 Async DateTime using System.Net; using System.Net.Sockets; using System.IO; private static AutoResetEvent connectionWaitHandle = new AutoResetEvent(false); static void Main(string[] args) { TcpListener listener = new TcpListener(1313); listener.Start(); while (true) { listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener); connectionWaitHandle.WaitOne(); //Wait until a client has begun handling an event } public static void DoAcceptTcpClientCallback(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient clientSocket = listener.EndAcceptTcpClient(ar); NetworkStream networkStream = clientSocket.GetStream(); System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream); streamWriter.WriteLine(DateTime.Now.ToLongTimeString()); streamWriter.Flush(); clientSocket.Close(); }

12/5/2015.net 13 Datagrams Datagram packets are used to implement a connectionless, packet based, delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. Packets may be lost or duplicated during transit. The class UdpClient represents a datagram in C#.

12/5/2015.net 14 Class UdpClient //Constructors public UdpClient () public UdpClient(int Port); // Methods public Connect(IPAddress); public BeginReceive(); public EndReceive(); void BeginSend(); void EndSend(); void Connect();

12/5/2015.net 15 Echo Services A common network service is an echo server An echo server simply sends packets back to the sender A client creates a packet, sends it to the server, and waits for a response. Echo services can be used to test network connectivity and performance. There are typically different levels of echo services. Each provided by a different layer in the protocol stack.

12/5/2015.net 16 UDPEchoClient.cs using System.Net.Sockets; using System.Net; class Program { static void Main(string[] args) { String message = "test"; UdpClient client = new UdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, " ", 5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] echo = client.Receive(ref RemoteIpEndPoint); Console.WriteLine("Received: " +Encoding.ASCII.GetString(echo)); client.Close(); Console.ReadKey(); }

12/5/2015.net 17 UDPEchoServer.cs using System.Net.Sockets; using System.Net; class Program { static void Main(string[] args) { UdpClient client = new UdpClient(5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { try { byte[] data = client.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(data); client.Send(data, data.Length, RemoteIpEndPoint); Console.WriteLine("Echoing: " + returnData); } catch (SocketException ex) { Console.WriteLine(ex.Message); }

What if we never get data? 12/5/2015.net 18 class Program { public static bool gotMessage = false; public static bool timeout = false; static void Main(string[] args) { Program pgm = new Program(); pgm.run(); } public void run() { String message = "test"; UdpClient client = new UdpClient(); Console.WriteLine("Sending: " + message); client.Send(Encoding.ASCII.GetBytes(message), 4, " ", 5050); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpState state = new UdpState(); state.cl = client; state.re = RemoteIpEndPoint; try { client.BeginReceive(ReceiveCallback, state); Timer timer = new Timer(TimerCallback); timer.Change(5000, Timeout.Infinite); while (!gotMessage && !timeout) { Thread.Sleep(100); if (timeout) { throw new SocketException(10060); } catch (SocketException ex) { Console.WriteLine("There was an error communicating with the server."); } Console.ReadKey(); }

What if we never get data? 12/5/2015.net 19 public void TimerCallback(object state) { timeout = true; } public void ReceiveCallback(IAsyncResult ar) { UdpClient cl = (UdpClient)((UdpState)(ar.AsyncState)).cl; IPEndPoint re = (IPEndPoint)((UdpState)(ar.AsyncState)).re; Byte[] echo = cl.EndReceive(ar, ref re); gotMessage = true; Console.WriteLine("Received: " + Encoding.ASCII.GetString(echo)); }

Using Raw Sockets 12/5/2015.net 20 The use of TcpClient and UdpClient in C# is convenient, but may not provide all the functionality we need (Timeouts for example). Using raw sockets are not significantly more complicated, but provide a lot more flexibility

Echo Client using sockets 12/5/2015.net 21 public void run() { String message = "test"; Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint server = new IPEndPoint(IPAddress.Parse(" "), 5050); client.ReceiveTimeout = 5000; Console.WriteLine("Sending: " + message); client.SendTo(Encoding.ASCII.GetBytes(message), server); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); EndPoint remoteServer = (EndPoint)RemoteIpEndPoint; byte[] data = new byte[1024]; try { int recv = client.ReceiveFrom(data, ref remoteServer); Console.WriteLine("Received: " + Encoding.ASCII.GetString(data)); } catch (SocketException) { Console.WriteLine("There was an error communicating with the server."); } Console.ReadKey(); }