Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 1 Laboratory 1 – Introduction to C# Exercises: You will need a logbook and USB memory stick for all the laboratory works in this module. Predict the outcomes of following programs in your logbook, then type them in, compile and run the programs. Hello1.cs __________________________________________________________ class Hello{ static void Main() { System.Console.WriteLine("hello, world"); } } ___________________________________________________________ To compile the code type “csc Hello1.cs”, this will create an executeable file called “Hello1.exe”. To run it type “Hello1.exe”. Hello2.cs ___________________________________________________________ using System; public class Hello2{ public static void Main() { Console.WriteLine("Hello, World!"); } } ___________________________________________________________ Hello3.cs ___________________________________________________________ // Hello3.cs using System; public class Hello3{ public static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine("You entered the following {0} command line arguments:", args.Length ); for (int i=0; i < args.Length; i++) { Console.WriteLine("{0}", args[i]); } } } ___________________________________________________________ To compile the code type “csc Hello3.cs”. To run it type “Hello3.exe 1 2 3 4”. Hello4.cs ___________________________________________________________ // Hello4.cs using System; public class Hello4{ public static int Main(string[] args) { Console.WriteLine("Hello, World!"); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 2 return 0; } } ___________________________________________________________ · Write a C# program (Repeat.cs) to print out all the words you typed in the command line, e.g. H:\Repeat.exe this is a test this is a test · Write a C# average program which can calculate the average value of 5 integers, the 5 integers can be taken from commend line input. Questions: 1. What kind of computer do you use at your home (or in the lab)? What is its configuration (CPU, RAM, Hard Disk, Monitor, Network/Sound card etc)? What is its operating system? 2. What are programming languages? Write down the names of all the programming languages you know, what are they mainly for and what are the characteristic features of C# language comparing to others? 3. What is a computer program? What are variables? What types of variables C# Java support? 4. What is the difference between statements and expressions? 5. In your own words, describe what is object-oriented programming, what is platform independent and what is multithreading. 6. What is Visual Studio .NET? What is .NET Framework? 7. What is Visual C# 2010 Express? Describe steps to download and install the software. 8. Use Windows XP/Vista/7 as an example, explain how to write, compile and run C# programs on Windows environment. References: http://www.csharp-station.com/ http://msdn.microsoft.com/en-us/library/aa288436%28v=vs.71%29.aspx http://msdn.microsoft.com/en-us/library/kx37x362.aspx http://msdn.microsoft.com/en-us/library/hh145618(VS.88).aspx http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm http://www.microsoft.com/visualstudio/en-us http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express http://msdn.microsoft.com/en-us/netframework/default.aspx Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 3 Laboratory 2 – Variables and Conditional Statements Exercises: Compile and run the following programmes and comment the results in your logbook. Binary.cs __________________________________________________________ using System; class Binary { public static void Main() { int x, y, result; float floatresult; x = 7; y = 5; result = x+y; Console.WriteLine("x+y: {0}", result); result = x-y; Console.WriteLine("x-y: {0}", result); result = x*y; Console.WriteLine("x*y: {0}", result); result = x/y; Console.WriteLine("x/y: {0}", result); floatresult = (float)x/(float)y; Console.WriteLine("x/y: {0}", floatresult); result = x%y; Console.WriteLine("x%y: {0}", result); result += x; Console.WriteLine("result+=x: {0}", result); } }___________________________________________________________ Unary.cs __________________________________________________________ using System; class Unary{ public static void Main(){ int unary = 0; int preIncrement; int preDecrement; int postIncrement; int postDecrement; int positive; int negative; Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 4 sbyte bitNot; bool logNot; preIncrement = ++unary; Console.WriteLine("pre-Increment: {0}", preIncrement); preDecrement = --unary; Console.WriteLine("pre-Decrement: {0}", preDecrement); postDecrement = unary--; Console.WriteLine("Post-Decrement: {0}", postDecrement); postIncrement = unary++; Console.WriteLine("Post-Increment: {0}", postIncrement); Console.WriteLine("Final Value of Unary: {0}", unary); positive = -postIncrement; Console.WriteLine("Positive: {0}", positive); negative = +postIncrement; Console.WriteLine("Negative: {0}", negative); bitNot = 0; bitNot = (sbyte)(~bitNot); Console.WriteLine("Bitwise Not: {0}", bitNot); logNot = false; logNot = !logNot; Console.WriteLine("Logical Not: {0}", logNot); } } ___________________________________________________________ IfSelect.cs __________________________________________________________ using System; class IfSelect{ public static void Main() { string myInput; int myInt; Console.Write("Please enter a number: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); if (myInt > 0){ Console.WriteLine("Your number {0} is greater than zero.", myInt); } else { Console.WriteLine("Your number {0} is equal or less than zero.", myInt); } } } Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 5 ___________________________________________________________ SwitchSelection.cs __________________________________________________________ using System; class SwitchSelect { public static void Main(){ string myInput; int myInt; Console.Write("Please enter a number between 1 and 3: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); switch (myInt){ case 1: Console.WriteLine("Your number is {0}.", myInt); break; case 2: Console.WriteLine("Your number is {0}.", myInt); break; case 3: Console.WriteLine("Your number is {0}.", myInt); break; default: Console.WriteLine("Your number {0} is not between 1 and 3.", myInt); break; } } } ___________________________________________________________ 1. Modify the above programme using the if ~ else statement. 2. Write a C# example programme using ?: conditional operator. 3. Write a C# program which can check a number is positive, negative or zero, the number is taken from the command line argument (e.g. args[0]). 4. Write a C# program which calculate the square root (use Math.Sqrt()) of a number, the number is taken from the command line argument (e.g. args[0]). Questions: 1. Define the terms of statements, expression, operators, variables and comments. 2. What are meanings of following expressions: x++, ++y, 20%7, x + =y, x -= y, x *= y, x /= y 3. What is the operator for Logical AND? Logical OR? 4. What is the syntax for if….else conditional statement? for switch statement? and ?: statement? Please give examples! Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 6 Laboratory 3 – Array and Loops Exercises: Predict the outcomes of the following program in your log book, then run the program on computer and compare the two results. Array.cs __________________________________________________________ using System; class Array{ public static void Main() { int[] myInts = { 5, 10, 15 }; bool[][] myBools = new bool[2][]; myBools[0] = new bool[2]; myBools[1] = new bool[1]; double[,] myDoubles = new double[2, 2]; string[] myStrings = new string[3]; Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]); myBools[0][0] = true; myBools[0][1] = false; myBools[1][0] = true; Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]); myDoubles[0, 0] = 3.147; myDoubles[0, 1] = 7.157; myDoubles[1, 1] = 2.117; myDoubles[1, 0] = 56.00138917; Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]); myStrings[0] = "Joe"; myStrings[1] = "Matt"; myStrings[2] = "Robert"; Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]); } } ___________________________________________________________ WhileLoop.cs ___________________________________________________________ using System; class WhileLoop{ public static void Main(){ int myInt = 0; while (myInt < 10){ Console.Write("{0} ", myInt); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 7 myInt++; } Console.WriteLine(); } } ___________________________________________________________ DoLoop.cs ___________________________________________________________ using System; class DoLoop{ public static void Main(){ string myChoice; do{ // Print A Menu Console.WriteLine("My Address Book\n"); Console.WriteLine("A - Add New Address"); Console.WriteLine("D - Delete Address"); Console.WriteLine("M - Modify Address"); Console.WriteLine("V - View Addresses"); Console.WriteLine("Q - Quit\n"); Console.WriteLine("Choice (A,D,M,V,or Q): "); // Retrieve the user's choice myChoice = Console.ReadLine(); // Make a decision based on the user's choice switch(myChoice) { case "A": case "a": Console.WriteLine("You wish to add an address."); break; case "D": case "d": Console.WriteLine("You wish to delete an address."); break; case "M": case "m": Console.WriteLine("You wish to modify an address."); break; case "V": case "v": Console.WriteLine("You wish to view the address list."); break; case "Q": case "q": Console.WriteLine("Bye."); break; default: Console.WriteLine("{0} is not a valid choice", myChoice); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 8 break; } // Pause to allow the user to see the results Console.Write("press Enter key to continue..."); Console.ReadLine(); Console.WriteLine(); } while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit } } ___________________________________________________________ ForLoop.cs ___________________________________________________________ using System; class ForLoop{ public static void Main(){ for (int i=0; i < 20; i++){ if (i == 10) break; if (i % 2 == 0) continue; Console.Write("{0} ", i); } Console.WriteLine(); } }___________________________________________________________ ForEachLoop.cs ___________________________________________________________ using System; class ForEachLoop{ public static void Main(){ string[] names = {"Cheryl", "Joe", "Matt", "Robert"}; foreach (string person in names){ Console.WriteLine("{0} ", person); } } } ___________________________________________________________ Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 9 Laboratory 4 - Method Exercises: 1. Predict the outcomes of the following program in your log book, then run the program on computer and compare the two results. 2. Modify the program, so that it has another method to calculate the subtraction of two integers. Method1.cs __________________________________________________________ using System; class Method1{ static void Main() { int x,y,z; x=5; y=3; z=AddTwo(x,y); Console.WriteLine("The sum is {0}",z); } static int AddTwo(int a, int b){ int sum=a+b; return sum; } } __________________________________________________________ · Write a C# program so that it uses a method called printperson(String x, int y) to print out a person’s name and age. · Write a C# program which can calculate the area of different shapes, e.g. rectangle (area(int x, int y)), triangle (area(int x, int y, int z)) or circle (area(int x)), using object-oriented approach and using overloading methods. · Define the terms of method overloading, write down the syntax. · Describe the keywords of public, protected and privates using examples! Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 10 Laboratory 5 - Networking 1 Exercises: 1. Predict the outcomes of the following programme in your log book, then run the program on computer and compare the two results. 2. Replace “http://www.lsbu.ac.uk /” with “http://www.google.co.uk/”, “http://www.bbc.co.uk”, how will these affect the result? 3. Modify the programme so that it can take any URL addresses from the command line argument. GetWebPage.cs __________________________________________________________ using System; using System.Net; using System.Text; using System.IO; namespace Test { class GetWebPage { public static void Main(string[] args) { String url=”http://www.lsbu.ac.uk”; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.ASCII); Console.WriteLine(streamReader.ReadToEnd()); } } }__________________________________________________________ 4. Modify the following programme, so that it displays the IP address of any given host. IPAddress.cs __________________________________________________________ using System; using System.Net; using System.Net.NetworkInformation; using System.Text; public class IPAddress0{ public static int Main (string [] args){ IPHostEntry host; string localIP = "?"; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList){ if (ip.AddressFamily.ToString() == "InterNetwork"){ localIP = ip.ToString(); Console.WriteLine("{0}", localIP); } } Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 11 return 0; } }__________________________________________________________ 5. Predict the outcomes of the following programmes in your log book, then run the program on computer and compare the two results. TCPStat.cs __________________________________________________________ using System; using System.Net; using System.Net.NetworkInformation; using System.Text; class TCPStat { public static void Main(string[] args) { ShowTcpStatistics(NetworkInterfaceComponent.IPv4); } public static void ShowTcpStatistics(NetworkInterfaceComponent version){ IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpStatistics tcpstat = null; Console.WriteLine(""); switch (version) { case NetworkInterfaceComponent.IPv4: tcpstat = properties.GetTcpIPv4Statistics(); Console.WriteLine("TCP/IPv4 Statistics:"); break; case NetworkInterfaceComponent.IPv6: tcpstat = properties.GetTcpIPv6Statistics(); Console.WriteLine("TCP/IPv6 Statistics:"); break; default: throw new ArgumentException("version"); // break; } Console.WriteLine(" Minimum Transmission Timeout............. : {0}", tcpstat.MinimumTransmissionTimeout); Console.WriteLine(" Maximum Transmission Timeout............. : {0}", tcpstat.MaximumTransmissionTimeout); Console.WriteLine(" Connection Data:"); Console.WriteLine(" Current ............................ : {0}", tcpstat.CurrentConnections); Console.WriteLine(" Cumulative .......................... : {0}", tcpstat.CumulativeConnections); Console.WriteLine(" Initiated ........................... : {0}", tcpstat.ConnectionsInitiated); Console.WriteLine(" Accepted ............................ : {0}", tcpstat.ConnectionsAccepted); Console.WriteLine(" Failed Attempts ..................... : {0}", tcpstat.FailedConnectionAttempts); Console.WriteLine(" Reset ............................... : {0}", tcpstat.ResetConnections); Console.WriteLine(""); Console.WriteLine(" Segment Data:"); Console.WriteLine(" Received ...............: {0}", tcpstat.SegmentsReceived); Console.WriteLine(" Sent ....................... : {0}", tcpstat.SegmentsSent); Console.WriteLine(" Retransmitted ....... : {0}", tcpstat.SegmentsResent); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 12 Console.WriteLine(""); } }__________________________________________________________ UDPStat.cs __________________________________________________________ using System; using System.Net; using System.Net.NetworkInformation; using System.Text; class UDPStat { public static void Main(string[] args){ ShowUdpStatistics(NetworkInterfaceComponent.IPv4); } public static void ShowUdpStatistics(NetworkInterfaceComponent version){ IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); UdpStatistics udpStat = null; switch (version){ case NetworkInterfaceComponent.IPv4: udpStat = properties.GetUdpIPv4Statistics(); Console.WriteLine("UDP IPv4 Statistics"); break; case NetworkInterfaceComponent.IPv6: udpStat = properties.GetUdpIPv6Statistics(); Console.WriteLine("UDP IPv6 Statistics"); break; default: throw new ArgumentException("version"); // break; } Console.WriteLine(" Datagrams Received .............. : {0}", udpStat.DatagramsReceived); Console.WriteLine(" Datagrams Sent ..................... : {0}", udpStat.DatagramsSent); Console.WriteLine("Incoming Datagrams Discarded: {0}", udpStat.IncomingDatagramsDiscarded); Console.WriteLine("Incoming Datagrams With Errors: {0}", udpStat.IncomingDatagramsWithErrors); Console.WriteLine(" UDP Listeners ........................: {0}", udpStat.UdpListeners); Console.WriteLine(""); } } __________________________________________________________ ICMPv4Stat.cs __________________________________________________________ using System; using System.Net; using System.Net.NetworkInformation; using System.Text; class ICMPv4Stat { public static void Main(string[] args) { ShowIcmpV4Statistics(); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 13 } public static void ShowIcmpV4Statistics(){ IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); IcmpV4Statistics stat = properties.GetIcmpV4Statistics(); Console.WriteLine("ICMP V4 Statistics:"); Console.WriteLine(" Messages ............................ Sent: {0,-10} Received: {1,-10}", stat.MessagesSent, stat.MessagesReceived); Console.WriteLine(" Errors .............................. Sent: {0,-10} Received: {1,-10}", stat.ErrorsSent, stat.ErrorsReceived); Console.WriteLine(" Echo Requests ....................... Sent: {0,-10} Received: {1,-10}", stat.EchoRequestsSent, stat.EchoRequestsReceived); Console.WriteLine(" Echo Replies ........................ Sent: {0,-10} Received: {1,-10}", stat.EchoRepliesSent, stat.EchoRepliesReceived); Console.WriteLine(" Destination Unreachables ............ Sent: {0,-10} Received: {1,-10}", stat.DestinationUnreachableMessagesSent, stat.DestinationUnreachableMessagesReceived); Console.WriteLine(" Source Quenches ..................... Sent: {0,-10} Received: {1,-10}", stat.SourceQuenchesSent, stat.SourceQuenchesReceived); Console.WriteLine(" Redirects ........................... Sent: {0,-10} Received: {1,-10}", stat.RedirectsSent, stat.RedirectsReceived); Console.WriteLine(" TimeExceeded ........................ Sent: {0,-10} Received: {1,-10}", stat.TimeExceededMessagesSent, stat.TimeExceededMessagesReceived); Console.WriteLine(" Parameter Problems .................. Sent: {0,-10} Received: {1,-10}", stat.ParameterProblemsSent, stat.ParameterProblemsReceived); Console.WriteLine(" Timestamp Requests .................. Sent: {0,-10} Received: {1,-10}", stat.TimestampRequestsSent, stat.TimestampRequestsReceived); Console.WriteLine(" Timestamp Replies ................... Sent: {0,-10} Received: {1,-10}", stat.TimestampRepliesSent, stat.TimestampRepliesReceived); Console.WriteLine(" Address Mask Requests ............... Sent: {0,-10} Received: {1,-10}", stat.AddressMaskRequestsSent, stat.AddressMaskRequestsReceived); Console.WriteLine(" Address Mask Replies ................ Sent: {0,-10} Received: {1,-10}", stat.AddressMaskRepliesSent, stat.AddressMaskRepliesReceived); Console.WriteLine(""); } }__________________________________________________________ · Define the terms of HTTP, URL, Ports, FTP, TCP, UDP and datagram. · What are Ports, what is the range? What range of port numbers are restricted? Give some examples of ports number of the well-know services, like HTTP, FTP, TELNET etc. Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 14 Laboratory 6 - Networking 2 Exercises: 1. Predict the outcomes of the following programmes in your log book, then run the program on computer and compare the two results. TcpServer.cs __________________________________________________________ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; class TcpServer{ public static void Main(){ TcpListener server=null; try{ // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while(true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while((i = stream.Read(bytes, 0, bytes.Length))!=0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 15 Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch(SocketException e){ Console.WriteLine("SocketException: {0}", e); } finally{ // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } __________________________________________________________ TcpClient.cs __________________________________________________________ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; class TcpClient{ public static void Main(string[] args){ Connect(args[0], args[1]); } static void Connect(String server, String message) { try { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, port // combination. Int32 port = 13000; TcpClient client = new TcpClient(server, port); // Translate the passed message into ASCII and store it as a Byte array. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 16 // Get a client stream for reading and writing. // Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response. // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.WriteLine("\n Press Enter to continue..."); Console.Read(); } }__________________________________________________________ UDPServer.cs __________________________________________________________ using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleUdpSrvr{ public static void Main(){ int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 17 Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, Remote); while(true){ data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); newsock.SendTo(data, recv, SocketFlags.None, Remote); } } } __________________________________________________________ UDPClient.cs __________________________________________________________ using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleUdpClient{ public static void Main() { byte[] data = new byte[1024]; string input, stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; int recv = server.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while(true){ Department of Engineering and Design Network Design & Implement Dr. Perry XIAO Copyright © 20011, London South Bank University 18 input = Console.ReadLine(); if (input == "exit") break; server.SendTo(Encoding.ASCII.GetBytes(input), Remote); data = new byte[1024]; recv = server.ReceiveFrom(data, ref Remote); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Stopping client"); server.Close(); } } __________________________________________________________ · Write a C# TCP echo client / server programme so that the server echoes back whatever the client send to it. · Write a C# UDP client / server program so that client can get time and date information from the server. · What is the purpose of try…catch…finally clause? What is error handling? · Define the terms of Socket and DatagramSocket.