1 / 43

Network Communications

Network Communications. A Brief Introduction. Reference. TCP/IP Sockets in C# Practical Guide for Programmers David B. Makofske Michael J. Donahooo Kenneth L. Calvert Morgan Kaufmann Publishers, 2004. Network Communications. IP Addresses. 32 bits 4 bytes

corin
Download Presentation

Network Communications

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 Communications A Brief Introduction

  2. Reference TCP/IP Sockets in C# Practical Guide for Programmers David B. Makofske Michael J. Donahooo Kenneth L. Calvert Morgan Kaufmann Publishers, 2004

  3. Network Communications

  4. IP Addresses • 32 bits • 4 bytes • Usually expressed as 4 decimal numbers in the range from 0 to 255, separated by dots • Example: • 131.247.3.219 (My office desktop computer) • 131.247.14.21 scorpius.eng.usf.edu • 131.247.3.1 grad.cse.usf.edu • 127.1.1.1 local host • All USF IP addresses begin with 131.247.

  5. What is my IP address? My office desktop computer.

  6. IP Addresses • An IP address corresponds to a destination on the Internet. • Typically one computer (host.) • Many programs may be running on that computer and all communicating on the Internet using the same IP address. • Multiplex using port numbers. • 16 bit unsigned numbers • 1 – 65,535

  7. Network Address Translation • NAT permits a single routable IP address to be shared among several computers. • Often implemented in home routers and corporate edge routers. • Between a private network and the Internet • Port number is used to translate the routable IP address to and from a private IP address. • Complicates connecting from the outside.

  8. Names • We normally identify hosts on the Internet by name. • google.com • cnn.com • grad.cse.usf.edu • Names are translated into IP addresses by the Domain Name System • or by a local configuration file. • All normal communication on the Internet uses IP addresses.

  9. Clients and Servers • Network communication is typically between a client and a server. • The client initiates communication. • Must know the IP address of the server and the port number of the application. • Like placing a telephone call. • The Server accepts requests from clients. • Does not know the IP address of the client in advance. • Like answering a telephone call. • The same computer and program can be a server for one conversation and a client for another.

  10. Sockets • A socket is an operating system construct used by a program to perform network I/O. • Similar to an open file. • Originally a Unix concept. • Later implemented in Windows. • Network communication is between sockets. • One program writes to a socket. • Another program reads from a socket. • The host operating systems at end points use the network to transport bytes between sockets.

  11. Internet Protocols • End to End Protocols • Transmission Control Protocol – TCP • User Datagram Protocol – UDP • Hop by Hop Protocol • Internet Protocol – IP

  12. Streams vs. Datagrams • TCP uses a connection between sockets to provide reliable byte stream transfer. • Bytes are delivered in the order sent. • UDP provides a datagram service. • Each datagram is handled independently • May be delivered out of order. • May be lost. • Both TCP and UDP use IP to transport packets across the Internet.

  13. Streams vs. Datagrams • A socket is uniquely identified by a Protocol (TCP or IP), an IP address, and a port number.

  14. TCP Connections • A TCP connection requires a setup phase. • “Handshake” between client an server. • Server listens for connection requests. • Client requests connection. • Server accepts connection request. • Once set up, the connection is a two-way communication channel. • Either party can sent bytes to the other.

  15. TCP • TCP is a byte stream protocol. • Bytes are not necessarily delivered in the same chunks that they were sent in.

  16. Talking to Yourself • Both ends of a network connection can be in the same computer. • Often done during development. • The IP address 127.1.1.1 means "this computer". • Looks the same to the application programs. • Uses most of the same operating system software. • Just bypasses the physical IO. • We will use this to demonstrate network IO without having to coordinate multiple computers.

  17. TCP Echo Client • The “Hello, world” of Network I/O. • Client connects to a TCP Echo Server and sends a message. • Then listens for a message from the server. • Server sends back the same message. • Client receives the message and outputs it to the console.

  18. TCP Echo Client • grad.cse.usf.edu has a TCP Echo Server which listens on Port 7. • Let’s write a client to send a message to it and output the echoed message to the console. • Create a new Windows console project. • TcpEchoClient

  19. Bytes vs. Strings • Normally in C# we work with chars and strings. • Network I/O works with bytes. • Not the same as chars! • In C# chars are Unicode. 16 bits. • We have to convert a string into an array of bytes in order to send it over a network connection. • When we receive on a network connection, we get an array of bytes. • Have to convert it into a string.

  20. Converting between Strings and Bytes • The .NET class Encoding provides the conversion functions that we need. • Documentation: • http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx • Convert C# string to byte array using ASCII encoding: • Encoding.ASCII.GetBytes(a_string); • Convert byte array to a C# string: • Encoding.ASCII.GetString(address, offset, count);

  21. TcpEchoClient • http://www.cse.usf.edu/~turnerr/Software_Systems_Development/Downloads/2011_04_26_Network_IO/TcpEchoClient.cs

  22. TcpEchoClient using System; using System.Text; using System.IO; using System.Net.Sockets; namespace TcpEchoClient { class Program { static void Main(string[] args) { String server = "grad.cse.usf.edu"; byte[] byteBuffer; int servPort = 7; TcpClient client = null; NetworkStream netStream = null; String msg = "Hello from the TCP Echo Client."; byteBuffer =Encoding.ASCII.GetBytes(msg);

  23. TcpEchoClient try { client = new TcpClient(server, servPort); netStream = client.GetStream(); netStream.Write(byteBuffer, 0, byteBuffer.Length); Console.WriteLine("Sent {0} bytes to server:\n{1}\n", byteBuffer.Length, msg); int totalBytesRcvd = 0; int bytesRcvd = 0; byte[] rcvBuffer = new byte[100]; while (totalBytesRcvd < byteBuffer.Length) { int bytesNeeded = byteBuffer.Length - totalBytesRcvd; bytesRcvd = netStream.Read(rcvBuffer, totalBytesRcvd, bytesNeeded); if (bytesRcvd == 0) { Console.WriteLine("Connection closed prematurely."); break; } totalBytesRcvd += bytesRcvd; } String rcvdString = Encoding.ASCII.GetString(rcvBuffer, 0, totalBytesRcvd); Console.WriteLine("Received {0} bytes: \n{1}", totalBytesRcvd, rcvdString); }

  24. TcpEchoClient catch (Exception e) { Console.WriteLine(e.Message); } finally { if (netStream != null) { netStream.Close(); } if (client != null) { client.Close(); } } Console.ReadLine(); } } }

  25. Program in Action

  26. Additional Features • We have basic network communcation. • Let’s add some features. • Let the user specify the server. • Let the user specify the message • Copy the .exe file to the C drive. • Open a command prompt window and run the program.

  27. TCP Echo Client Running

  28. Let the user specify the server //String server = "grad.cse.usf.edu"; String server = "131.247.3.219"; byte[] byteBuffer; int servPort = 7; TcpClient client = null; NetworkStream netStream = null; String msg = "Hello from the TCP Echo Client."; if (args.Length > 0) { // Use first command line argument as server ID server = args[0]; }

  29. Program Running from the Command Prompt

  30. Let the user specify the message if (args.Length > 1) { msg = args[1]; for (int i = 2; i < args.Length; i++) { msg += " " + args[i]; } } byteBuffer = Encoding.ASCII.GetBytes(msg);

  31. Program Running from the Command Prompt Keep window open. End of Section

  32. Implementing a Server • A server application must accept connection requests from the network. • .NET makes this easy with the TcpListener class. • Documentation: • http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

  33. TCP Echo Server • The TCP Echo Server creates a TcpListener object and starts it. • Repeats forever: • Wait for connection request. • Accept connection • Repeat until client closes connection: • Read from connection. • Output received characters to the connection. • Output received characters to console.

  34. TCP Echo Server • Create a new C# console application project. • TcpEchoServer • http://www.cse.usf.edu/~turnerr/Software_Systems_Development/Downloads/2011_04_26_Network_IO/TcpEchoServer.cs

  35. TCP Echo Server using System; using System.Text; using System.Net; using System.Net.Sockets; namespace TcpEchoServer { class Program { private const int BUFSIZE = 32;

  36. TCP Echo Server static void Main(string[] args) { int servPort = 7; TcpListener listener = null; Console.WriteLine("TCP Echo Server starting\n"); try { listener = new TcpListener(IPAddress.Any, servPort); listener.Start(); } catch (SocketException se) { Console.WriteLine(se.ErrorCode + ": " + se.Message); Console.ReadLine(); Environment.Exit(se.ErrorCode); } byte[] rcvBuffer = new byte[BUFSIZE]; int bytesRcvd;

  37. TCP Echo Server (continued) while (true) { TcpClient client = null; NetworkStream netStream = null; try { client = listener.AcceptTcpClient(); netStream = client.GetStream(); Console.WriteLine("Connection accepted"); int totalBytesEchoed = 0; while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) { netStream.Write(rcvBuffer, 0, bytesRcvd); totalBytesEchoed += bytesRcvd; String rcvd_msg = Encoding.ASCII.GetString(rcvBuffer, 0, bytesRcvd); Console.WriteLine("Echoed {0} characters: \n{1}", bytesRcvd, rcvd_msg); } Console.WriteLine("Connection closed"); netStream.Close(); client.Close(); }

  38. TCP Echo Server catch (Exception e) { Console.WriteLine(e.Message); if (netStream != null) { netStream.Close(); } Console.ReadLine(); } } } } }

  39. Try it! • Build and run the server • Back in the command prompt window for the client, give the command: TcpEchoClient 127.1.1.1 hello local server

  40. Client Window

  41. Server Window

  42. Client Window

  43. Server Window End of Presentation

More Related