Chapter Five Networking in Java 1 Networking Basics

Chapter Five Networking in Java 1

Networking Basics • Computer networking is to send and receive messages among computers on the Internet • To browse the Web or send email, your computer must be connected to the Internet. • Your computer can connect to the Internet through an Internet Service Provider (ISP) using a dialup, DSL, or cable modem, or through a local area network (LAN). • Java Networking is a concept of connecting two or more computing devices together so that we can share resources. • Advantage of Java Networking – sharing resources – centralize software management • When a computer needs to communicate with another computer, it needs to know an IP address. 2

Networking Basics • Internet Protocol (IP) addresses – Uniquely identifies the computer on the Internet. or – IP address is a unique number assigned to a node of a network. – It is a logical address that can be changed. – Every host on Internet has a unique IP address – An IP address consists of four dotted decimal numbers ranging from 0 and 255, such as 143. 89. 40. 46, 203. 184. 197. 198 203. 184. 197. 196, 203. 184. 197, 127. 0. 0. – Since it is difficult to remember IP address, there is a special server called Domain Name Server(DNS), which translates hostname to IP address – Example: Domain. Name: www. bdu. et , www. google. com, localhost IP Addresess: 10. 1. 25. 16 216. 58. 207. 4 127. 0. 0. 1 – One domain name can correspond to multiple internet addresses: • www. yahoo. com: 66. 218. 70. 49; 66. 218. 70. 50; 66. 218. 71. 84; … – Domain Name Server (DNS) maps names to numbers 3

Networking Basics l l A protocols is a set of rules that facilitate communications between machines or hosts. Examples: § HTTP: Hyper. Text Transfer Protocol § FTP: File Transfer Protocol § SMTP: Simple Message Transfer Protocol § TCP: Transmission Control Protocol § UDP: User Datagram Protocol, good for, e. g. , video delivery) TCP: § Connection-oriented protocol § enables two hosts to establish a connection and exchange streams of data. § Acknowledgement is send by the receiver. So, it is reliable but slow § Uses Stream-based communications § guarantees delivery of data and also guarantees that packets will be delivered in the same order in which they were sent. UDP: § Enables connectionless communication § Acknowledgement is not sent by the receiver. So it is not reliable but fast. § Uses packet-based communications. § Cannot guarantee lossless transmission. 4

Networking Basics l Port Number § The port number is used to uniquely identify different applications. § It acts as a communication endpoint between applications. § The port number is associated with the IP address for communication between two applications. § Port numbers are ranging from 0 to 65536, but port numbers 0 to 1024 are reserved for privileged services. § Many standard port numbers are pre-assigned § You can choose any port number that is not currently used by other programs. § IP address + port number = "phone number " for service or application MAC Address § MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). § A network node can have multiple NIC but each with unique MAC. 5 § l time of day 13, ftp 21, telnet 23, smtp 25, http 80

Networking Basics l Client-Server interaction l Communication between hosts is two-way, but usually the two hosts take different roles. l Server waits for client to make request Server registered on a known port with the host ("public phone number") Listens for incoming client connections l Client "calls" server to start a conversation Client making calls uses hostname/IP address and port number Sends request and waits for response l Standard services always running ftp, http, smtp, etc. server running on host using expected port l Server offers shared resource (information, database, files, printer, compute power) to clients 6

Socket-Level Programming l Java Socket programming is used for communication between the applications running on different JRE. l Java Socket programming can be connection-oriented or connectionless. l Socket and Server. Socket classes are used for connection-oriented socket programming. l Datagram. Socket and Datagram. Packet classes are used for connection-less socket programming. l Java socket programming provides facility to share data between different computing devices. l Send and receive data using streams Output. Stream Input. Stream Client Server Input. Stream Output. Stream 7

Client/Server Communications • Java provides the Server. Socket class for creating a server socket and the Socket class for creating a client socket. • Two programs on the Internet communicate through a server socket and a client socket using I/O streams. • Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. • Network programming usually involves a server and one or more clients. • The client sends requests to the server, and the server responds. • The client begins by attempting to establish a connection to the server. • The server can accept or deny the connection. • Once a connection is established, the client and the server communicate through sockets. • The server must be running when a client attempts to connect to the server. 8 • The server waits for a connection request from a client.

Client/Server Communications The statements needed to create sockets on a server and a client are shown below. 9

Server Sockets • To establish a server, you need to create a server socket and attach it to a port, which is where the server listens for connections. • The port identifies the TCP service on the socket. • The following statement creates a server socket server. Socket: Server. Socket server. Socket = new Server. Socket(port); • Attempting to create a server socket on a port already in use would cause the java. net. Bind. Exception. 10

Client Sockets • After a server socket is created, the server can use the following statement to listen for connections: Socket socket = server. Socket. accept(); • This statement waits until a client connects to the server socket. • The client issues the following statement to request a connection to a server: Socket socket = new Socket(server. Name, port); • This statement opens a socket so that the client program can communicate with the server. 11

Client Sockets • server. Name is the server’s Internet host name or IP address. • The following statement creates a socket on the client machine to connect to the host 130. 254. 204. 33 at port 8000: • Socket socket = new Socket("130. 254. 204. 33", 8000) • Alternatively, you can use the domain name to create a socket, as follows: Socket socket = new Socket(“www. google. com", 8000); • When you create a socket with a host name, the JVM asks the DNS to translate the host name into the IP address. 12

Data Transmission through Sockets • After the server accepts the connection, communication between the server and client is conducted the same as for I/O streams. • The statements needed to create the streams and to exchange data between them are shown in the Figure below. 13

Data Transmission through Sockets 14

Data Transmission through Sockets • To get an input stream and an output stream, use the get. Input. Stream() and get. Output. Stream() methods on a socket object. • For example, the following statements create an Input. Stream stream called input and an Output. Stream stream called output from a socket: Input. Stream input = socket. get. Input. Stream(); Output. Stream output = socket. get. Output. Stream(); Data. Input. Stream in = new Data. Input. Stream(input); Data. Output. Stream out = new Data. Output. Stream(output)); 15

Data Transmission through Sockets • The Input. Stream and Output. Stream streams are used to read or write bytes. • You can use Data. Input. Stream, Data. Output. Stream, Buffered. Reader, and Print. Writer to wrap on the Input. Stream and Output. Stream to read or write data, such as int, double, or String. • The following statements, for instance, create the Data. Input. Stream stream input and the Data. Output. Stream stream output to read and write primitive data values: Data. Input. Stream input = new Data. Input. Stream (socket. get. Input. Stream()); Data. Output. Stream output = new Data. Output. Stream (socket. get. Output. Stream()); • The server can use input. read. Double() to receive a double value from the client, and output. write. Double(d) to send the double value d to the client. • Binary I/O is more efficient than text I/O because text I/O requires encoding and decoding. • Therefore, it is better to use binary I/O for transmitting data between a server and a client to improve performance. 16

A Client/Server Example • Problem: Write a client and a server program that the client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. In this example, the data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. The client sends the radius to the server; the server computes the area and sends it to the client. 17

A Client/Server Example • The client sends the radius through a Data. Output. Stream on the output stream socket, and the server receives the radius through the Data. Input. Stream on the input stream socket, as shown in Figure (A) below. • The server computes the area and sends it to the client through a Data. Output. Stream on the output stream socket, and the client receives the area through a Data. Input. Stream on the input stream socket, as shown in Figure (B) below. 18

A Client/Server Example Note: Start the server, then the client. 19

A Client/Server Example import import java. io. *; java. net. *; java. util. *; java. awt. *; javax. swing. *; public class Server extends JFrame { // Text area for displaying contents private JText. Area jta = new JText. Area(); public static void main(String[] args) { new Server(); } public Server() { // Place text area on the frame set. Layout(new Border. Layout()); add(new JScroll. Pane(jta), Border. Layout. CENTER); set. Title("Server"); set. Size(500, 300); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Visible(true); // It is necessary to show the frame here! 20

A Client/Server Example try { // Create a server socket Server. Socket server. Socket = new Server. Socket(8000); jta. append("Server started at " + new Date() + 'n' ); // Listen for a connection request Socket socket = server. Socket. accept(); // Create data input and output streams Data. Input. Stream input. From. Client = new Data. Input. Stream(socket. get. Input. Stream()); Data. Output. Stream output. To. Client = new Data. Output. Stream(socket. get. Output. Stream()); while (true) { // Receive radius from the client double radius = input. From. Client. read. Double(); double area = radius * Math. PI; // Compute area // Send area back to the client output. To. Client. write. Double(area); jta. append("Radius received from client: " + radius + 'n' ); jta. append("Area found: " + area + 'n' ); } } catch(IOException ex) { System. err. println(ex); } } } 21

A Client/Server Example import java. io. *; import java. net. *; import java. awt. event. *; import javax. swing. *; public class Client extends JFrame { // Text field for receiving radius private JText. Field jtf = new JText. Field(); // Text area to display contents private JText. Area jta = new JText. Area(); // IO streams private Data. Output. Stream to. Server; private Data. Input. Stream from. Server; public static void main(String[] args) { new Client(); } public Client() { // Panel p to hold the label and text field JPanel p = new JPanel(); p. set. Layout(new Border. Layout()); p. add(new JLabel("Enter radius"), Border. Layout. WEST); p. add(jtf, Border. Layout. CENTER); jtf. set. Horizontal. Alignment(JText. Field. RIGHT); set. Layout(new Border. Layout()); add(p, Border. Layout. NORTH); add(new JScroll. Pane(jta), Border. Layout. CENTER); jtf. add. Action. Listener(new Text. Field. Listener()); set. Title("Client"); set. Size(500, 300); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Visible(true); // It is necessary to show the frame here! 22

A Client/Server Example try { // Create a socket to connect to the server Socket socket = new Socket("localhost", 8000); // Socket socket = new Socket("130. 254. 204. 33", 8000); Socket socket = new Socket("liang. armstrong. edu", 8000); // Create an input stream to receive data from the server from. Server = new Data. Input. Stream(socket. get. Input. Stream()); // Create an output stream to send data to the server to. Server = new Data. Output. Stream(socket. get. Output. Stream()); } catch (IOException ex) { jta. append(ex. to. String() + 'n' ); } } 23

A Client/Server Example private class Text. Field. Listener implements Action. Listener { @Override public void action. Performed(Action. Event e) { try { // Get the radius from the text field double radius = Double. parse. Double(jtf. get. Text(). trim()); // Send the radius to the server to. Server. write. Double(radius); to. Server. flush(); // Get area from the server double area = from. Server. read. Double(); // Display to the text area jta. append("Radius is " + radius + "n"); jta. append("Area received from the server is “+area+ 'n'); } catch (IOException ex) { System. err. println(ex); } } 24

The Inet. Address Class • The server program can use the Inet. Address class to obtain the information about the IP address and host name for the client. • You can use the Inet. Address class to find the client’s host name and IP address. • You can use the statement shown below to create an instance of Inet. Address for the client on a socket. Inet. Address inet = socket. get. Inet. Address(); • Next, you can display the client’s host name and IP address, as follows: System. out. println("Client's host name is " + inet. get. Host. Name()); System. out. println("Client's IP Address is " + inet. get. Host. Address()); • You can also create an instance of Inet. Address from a host name or IP address using the static get. By. Name() method. • For example, the following statement creates an Inet. Address for the host www. bdu. et. Inet. Address address = Inet. Address. get. By. Name(“www. bdu. et"); 25

Example: The Inet. Address Class import java. net. *; public class Identify. Host. Name. IP { public static void main(String[] args) { try { Inet. Address address = Inet. Address. get. By. Name("www. bdu. et"); System. out. print("Host name: "+ address. get. Host. Name()); System. out. println("IP address: "+ address. get. Host. Address()); } catch (Unknown. Host. Exception ex) { System. err. println("Unknown host or IP address www. bdu. et "); } } } 26

Serving Multiple Clients § § § A server can serve multiple clients. The connection to each client is handled by one thread. Multiple clients are quite often connected to a single server at the same time. You can use threads to handle the server's multiple clients simultaneously. Simply create a thread for each connection. Here is how the server handles the establishment of a connection: while (true) { Socket socket = server. Socket. accept(); Thread thread = new Thread. Class(socket); thread. start(); } § The server socket can have many connections. § Each iteration of the while loop creates a new connection. § Whenever a connection is established, a new thread is created to handle communication between the server and the new client; and this allows multiple connections to run at the same time. 27

Example: Serving Multiple Clients Note: Start the server first, then start multiple clients. 28

Example: Serving Multiple Clients • import java. io. *; import java. net. *; import java. util. *; import java. awt. *; import javax. swing. *; public class Multi. Thread. Server extends JFrame { // Text area for displaying contents private JText. Area jta = new JText. Area(); public static void main(String[] args) { new Multi. Thread. Server(); } public Multi. Thread. Server() { // Place text area on the frame set. Layout(new Border. Layout()); add(new JScroll. Pane(jta), Border. Layout. CENTER); set. Title("Multi. Thread. Server"); set. Size(500, 300); set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); set. Visible(true); // It is necessary to show the frame here! try { // Create a server socket Server. Socket server. Socket = new Server. Socket(8000); jta. append("Multi. Thread. Server started at " + new Date() + 'n' ); // Number a client int client. No = 1; 29

Example: Serving Multiple Clients • while (true) { // Listen for a new connection request Socket socket = server. Socket. accept(); // Display the client number jta. append("Starting thread for client " + client. No + " at " + new Date() + 'n' ); // Find the client's host name and IP address Inet. Address inet. Address = socket. get. Inet. Address(); jta. append("Client " + client. No + "'s host name is “ + inet. Address. get. Host. Name() + "n"); jta. append("Client " + client. No + "'s IP Address is “ + inet. Address. get. Host. Address() + "n"); // Create a new thread for the connection Handle. AClient task = new Handle. AClient(socket); // Start the new thread new Thread(task). start(); // Increment client. No++; } } catch(IOException ex) { System. err. println(ex); } } 30

Example: Serving Multiple Clients // Inner class // Define thread class for handling new connection class Handle. AClient implements Runnable { private Socket socket; // A connected socket /** Construct a thread */ public Handle. AClient(Socket socket) { this. socket = socket; } @Override /** Run a thread */ public void run(){ try { // Create data input and output streams Data. Input. Stream input. From. Client = new Data. Input. Stream(socket. get. Input. Stream()); Data. Output. Stream output. To. Client = new Data. Output. Stream(socket. get. Output. Stream()); // Continuously serve the client while (true) { // Receive radius from the client double radius = input. From. Client. read. Double(); // Compute area double area = radius * Math. PI; // Send area back to the client output. To. Client. write. Double(area); jta. append("radius received from client: " + radius + 'n' ); jta. append("Area found: " + area + 'n' ); } } catch(IOException e) { System. err. println(e); } } 31

Sending and Receiving Objects • A program can send and receive objects from another program. • In the preceding examples, you learned how to send and receive data of primitive types. • You can also send and receive objects using Object. Output. Stream and Object. Input. Stream on socket streams. • To enable passing, the objects must be serializable. • The following example demonstrates how to send and receive objects. 32

Example: Passing Objects in Network Programs Write a program that collects student information from a client and send them to a server. Passing student information in an object. 33

Example: Passing Objects in Network Programs public class Student. Address implements java. io. Serializable { private String name; private String street; private String city; private String state; private String zip; public Student. Address(String name, String street, String city, String state, String zip) { this. name = name; this. street = street; this. city = city; this. state = state; this. zip = zip; } public String get. Name() { return name; } public String get. Street() { return street; } public String get. City() { return city; } public String get. State() { return state; } public String get. Zip() { return zip; } } 34

Example: Passing Objects in Network Programs import java. io. *; import java. net. *; import java. awt. event. *; import javax. swing. border. *; public class Student. Client extends JApplet { private JText. Field jtf. Name = new JText. Field(32); private JText. Field jtf. Street = new JText. Field(32); private JText. Field jtf. City = new JText. Field(20); private JText. Field jtf. State = new JText. Field(2); private JText. Field jtf. Zip = new JText. Field(5); // Button for sending a student's address to the server private JButton jbt. Register = new JButton("Register to the Server"); // Indicate if it runs as application private boolean is. Stand. Alone = false; // Host name or IP address String host = "localhost"; public void init() { // Panel p 1 for holding labels Name, Street, and City JPanel p 1 = new JPanel(); p 1. set. Layout(new Grid. Layout(3, 1)); p 1. add(new JLabel("Name")); p 1. add(new JLabel("Street")); p 1. add(new JLabel("City")); 35

Example: Passing Objects in Network Programs // Panel jp. State for holding state JPanel jp. State = new JPanel(); jp. State. set. Layout(new Border. Layout()); jp. State. add(new JLabel("State"), Border. Layout. WEST); jp. State. add(jtf. State, Border. Layout. CENTER); // Panel jp. Zip for holding zip JPanel jp. Zip = new JPanel(); jp. Zip. set. Layout(new Border. Layout()); jp. Zip. add(new JLabel("Zip"), Border. Layout. WEST); jp. Zip. add(jtf. Zip, Border. Layout. CENTER); // Panel p 2 for holding jp. State and jp. Zip JPanel p 2 = new JPanel(); p 2. set. Layout(new Border. Layout()); p 2. add(jp. State, Border. Layout. WEST); p 2. add(jp. Zip, Border. Layout. CENTER); // Panel p 3 for holding jtf. City and p 2 JPanel p 3 = new JPanel(); p 3. set. Layout(new Border. Layout()); p 3. add(jtf. City, Border. Layout. CENTER); 36

Example: Passing Objects in Network Programs • p 3. add(p 2, Border. Layout. EAST); // Panel p 4 for holding jtf. Name, jtf. Street, and p 3 JPanel p 4 = new JPanel(); p 4. set. Layout(new Grid. Layout(3, 1)); p 4. add(jtf. Name); p 4. add(jtf. Street); p 4. add(p 3); // Place p 1 and p 4 into Student. Panel JPanel student. Panel = new JPanel(new Border. Layout()); student. Panel. set. Border(new Bevel. Border(Bevel. Border. RAISED)); student. Panel. add(p 1, Border. Layout. WEST); student. Panel. add(p 4, Border. Layout. CENTER); // Add the student panel and button to the applet add(student. Panel, Border. Layout. CENTER); add(jbt. Register, Border. Layout. SOUTH); // Register listener jbt. Register. add. Action. Listener(new Button. Listener()); // Find the IP address of the Web server if (!is. Stand. Alone) host = get. Code. Base(). get. Host(); } /** Handle button action */ private class Button. Listener implements Action. Listener { @Override public void action. Performed(Action. Event e) { try { // Establish connection with the server Socket socket = new Socket(host, 8000); 37

Example: Passing Objects in Network Programs // Create an output stream to the server Object. Output. Stream to. Server = new Object. Output. Stream(socket. get. Output. Stream()); // Get text field String name = jtf. Name. get. Text(). trim(); String street = jtf. Street. get. Text(). trim(); String city = jtf. City. get. Text(). trim(); String state = jtf. State. get. Text(). trim(); String zip = jtf. Zip. get. Text(). trim(); // Create a Student. Address object and send to the server Student. Address s = new Student. Address(name, street, city, state, zip); to. Server. write. Object(s); } catch (IOException ex) { System. err. println(ex); } } } 38

Example: Passing Objects in Network Programs /** Run the applet as an application */ public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Register Student Client"); // Create an instance of the applet Student. Client applet = new Student. Client(); applet. is. Stand. Alone = true; // Get host if (args. length == 1) applet. host = args[0]; // Add the applet instance to the frame. add(applet, Border. Layout. CENTER); // Invoke init() and start() applet. init(); applet. start(); // Display the frame. pack(); frame. set. Visible(true); } } 39

Example: Passing Objects in Network Programs • import java. io. *; import java. net. *; public class Student. Server { private Object. Output. Stream output. To. File; private Object. Input. Stream input. From. Client; public static void main(String[] args) { new Student. Server(); } public Student. Server() { try { // Create a server socket Server. Socket server. Socket = new Server. Socket(8000); System. out. println("Server started "); // Create an object output stream output. To. File = new Object. Output. Stream( new File. Output. Stream("student. dat", true)); while (true) { // Listen for a new connection request Socket socket = server. Socket. accept(); // Create an input stream from the socket input. From. Client = new Object. Input. Stream(socket. get. Input. Stream()); 40

Example: Passing Objects in Network Programs // Read from input Object object = input. From. Client. read. Object(); // Write to the file output. To. File. write. Object(object); System. out. println("A new student object is stored"); } } catch(Class. Not. Found. Exception ex) { ex. print. Stack. Trace(); } catch(IOException ex) { ex. print. Stack. Trace(); } finally { try { input. From. Client. close(); output. To. File. close(); } catch (Exception ex) { ex. print. Stack. Trace(); } } 41

The URL Class § Audio and images are stored in files. § The java. net. URL class can be used to identify the files on the Internet. § In general, a URL (Uniform Resource Locator) is a pointer to a "resource" on the World Wide Web. § A resource can be something as simple as a file or a directory. § You can create a URL object using the following constructor: public URL(String spec) throws Malformed. URLException § For example, the following statement creates a URL object for http: //www. sun. com: try { URL url = new URL("http: //www. sun. com"); } catch(Malformed. URLException ex) { } 42

Creating a URL Instance § To retrieve the file, first create a URL object for the file. § For example, the following statement creates a URL object for http: //www. cs. armstrong. edu/liang/index. html. URL url = new URL("http: //www. cs. armstrong. edu/liang/index. html"); § You can then use the open. Stream() method defined in the URL class to open an input stream to the file's URL. Input. Stream input. Stream = url. open. Stream(); 43

The End!! 44
- Slides: 44