430 likes | 606 Views
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
E N D
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
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.
What is my IP address? My office desktop computer.
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
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.
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.
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.
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.
Internet Protocols • End to End Protocols • Transmission Control Protocol – TCP • User Datagram Protocol – UDP • Hop by Hop Protocol • Internet Protocol – IP
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.
Streams vs. Datagrams • A socket is uniquely identified by a Protocol (TCP or IP), an IP address, and a port number.
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.
TCP • TCP is a byte stream protocol. • Bytes are not necessarily delivered in the same chunks that they were sent in.
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.
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.
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
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.
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);
TcpEchoClient • http://www.cse.usf.edu/~turnerr/Software_Systems_Development/Downloads/2011_04_26_Network_IO/TcpEchoClient.cs
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);
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); }
TcpEchoClient catch (Exception e) { Console.WriteLine(e.Message); } finally { if (netStream != null) { netStream.Close(); } if (client != null) { client.Close(); } } Console.ReadLine(); } } }
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.
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]; }
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);
Program Running from the Command Prompt Keep window open. End of Section
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
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.
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
TCP Echo Server using System; using System.Text; using System.Net; using System.Net.Sockets; namespace TcpEchoServer { class Program { private const int BUFSIZE = 32;
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;
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(); }
TCP Echo Server catch (Exception e) { Console.WriteLine(e.Message); if (netStream != null) { netStream.Close(); } Console.ReadLine(); } } } } }
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
Server Window End of Presentation