Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Advanced Programming

/
Java Programming
By Melese E.

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 1


Advanced Programming
/
Java Programming

Networking in Java

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 2


Networking in Java – Overview
• Socket (Berkeley socket) – identifies an endpoint in a network
• Sockets are at the foundation of modern networking because a socket allows a single computer to
serve many different clients at once, as well as to serve many different types of information
• This is accomplished through the use of a port, which is a numbered socket on a particular machine.
• A server process is said to "listen" to a port until a client connects to it.
• A server is allowed to accept multiple clients connected to the same port number, although each session is
unique.
• To manage multiple client connections, a server process must be multithreaded or have some other means of multiplexing the
simultaneous I/O
• Socket communication takes place via a protocol.
• Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an
address across a network, which does not guarantee to deliver said packets to the destination.
• Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these
packets, sorting and retransmitting them as necessary to reliably transmit data.
• A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets
• The application layer is identified by the use of ports
• TCP/IP reserves the lower 1,024 ports for specific protocols.
• A few might be familiar to you. For example, port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois; 80 is for
HTTP; 119 is for netnews.

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 3


Networking in Java – Overview
• A key component of the Internet (or networking in generals) is the address.
• Every computer on the Internet has one.
• An Internet address is a number that uniquely identifies each computer on the Net
• IPv4 address – 32 bit
• IPv6 address – 128 bit
• Just as the numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describes a machine’s location in a name space
• For example, www.google.com
• Domain names are human readable
• But, the computer uses IP addresses to uniquely identify devices
• DNS (Domain Name System) – is an application layer protocol which is in charge of converting
domain names into IP address and vice versa
• In Java, you can develop network applications Socket Programming
• Using TCP – connection-oriented reliable transport layer protocol
• Using UDP – connectionless unreliable transport layer protocol
• Using RMI – the ability to call a method on a remote computer
• Java’s networking related classes are defined in the java.net package
• Beginning with JDK 11, Java has also provided enhanced networking support for HTTP clients in
the java.net.http package

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 4


Networking in Java – Socket Programming
• Socket – IP address + Port
• IP address – identifies the device (computer)
• Port – identifies the application on the device
• There are two kinds of TCP sockets in Java.
• One is for servers, and the other is for clients.
• The ServerSocket class is designed to be a "listener," which waits for clients to
connect before doing anything.
• Thus, ServerSocket is for servers.
• The Socket class is for clients.
• It is designed to connect to server sockets and initiate protocol exchanges

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 5


Networking in Java – Socket Programming
• The client – using TCP socket
• The creation of a Socket object implicitly establishes a connection between the client and
server.
• There are no methods or constructors that explicitly expose the details of establishing that connection
• The two constructors of the Socket class are
• Socket(String hostName, int port) throws UnknownHostException, IOException – Creates a socket
connected to the named host and port
• Socket(InetAddress ipAddress, int port) throws IOException – Creates a socket using a preexisting
InetAddress object and a port
• Some of the methods of Socket instance are
• InetAddress getInetAddress( ) – Returns the InetAddress associated with the Socket object. It returns null
if the socket is not connected
• int getPort() – Returns the remote port to which the invoking Socket object is connected. It returns 0 if
the socket is not connected
• int getLocalPort() – Returns the local port to which the invoking Socket object is bound. It returns –1 if
the socket is not bound
• InputStream getInputStream( ) throws IOException – Returns s the InputStream associated with the
invoking socket
• OutputStream getOutputStream( ) throws IOException – Returns the OutputStream associated with the
invoking socket
• void close() – closes the connection
Wednesday, May 29, 2024 By Melese E., Department of Computer Science 6
Networking in Java – Socket Programming
import java.net.*;
import java.io.*;
public class ClientSocket {
public static void main(String[] args)throws Exception{
Socket soc = new Socket("localhost", 5000);
InputStream in = soc.getInputStream(); //byte oriented
OutputStream out = soc.getOutputStream(); //byte oriented
//You can attach these io objects to other streams
BufferedReader br = new BufferedReader(new InputStreamReader(in)); //character oriented
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); //character oriented
bw.write("message for the server");
int c;
while((c = br.read()) != -1){
System.out.println((char)c);
}
soc.close();
}
}

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 7


Networking in Java – Socket Programming
• The Server – using TCP socket
• The ServerSocket class is used to create servers that listen for either local or
remote client programs to connect to them on published ports.
• ServerSockets are quite different from client Sockets.
• When you create a ServerSocket, it will register itself with the system as having an
interest in client connections.
• The constructors for ServerSocket reflect the port number that you want to accept
connections on and, optionally, how long you want the queue for said port to be.
• The constructors of the ServerSocket class
• ServerSocket(int port) throws IOException – Creates server socket on the specified port
with a queue length of 50
• ServerSocket(int port, int maxQueue) throws IOException – Creates a server socket on
the specified port with a maximum queue length of maxQueue
• The methods
• Socket accept() - which is a blocking call that will wait for a client to initiate
communications and then return with a normal Socket that is then used for
communication with the client

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 8


Networking in Java – Socket Programming
import java.net.*;
import java.io.*;
public class TheServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(50001);
Socket soc = ss.accept();

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));


BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
System.out.println(soc.getPort());
bw.write("This is a message from the server");
bw.flush();
int a;
while((a=br.read()) != -1){
System.out.print((char)a);
}
soc.close();
}
}

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 9


Networking in Java – Socket Programming

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 10


Networking in Java – Socket Programming
• Some important classes of the java.net package
• InetAddress class – used to work with IPv4 / IPv6 addresses – uses factory
methods to create an object of InetAddress
• URL class – used to create Uniform Resource Locator (URL)
• DatagramSocket – to work with UDP
• DatagramPacket – to work with UDP
• URLConnection – to get connected to a specified URL and analyze the
connection
• UnknownHostException – an exception thrown when trying to connect to an
unknown server
• MalformedURLException – an exception thrown when the string representing
the URL is incorrect

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 11


Networking in Java – Remote Method Invocation
• Remote Method Invocation (RMI) allows a Java object that executes
on one machine to invoke a method of a Java object that executes on
another machine
• This is an important feature, because it allows you to build distributed
applications
• The java.rmi package contains classes for creating RMI applications –
some of the important ones are
• Remote interface
• Naming class
• RemoteException and NotBoundException classes
• The java.rmi.server package provides classes for creating an RMI
server – the important one is
• UnicastRemoteObject class
• The MalformedURLException from java.net package is also important
Wednesday, May 29, 2024 By Melese E., Department of Computer Science 12
Networking in Java – Remote Method Invocation
• Steps in creating RMI Server and Client
• Step One: Create an interface that extends the Remote interface
• This interface specifies the methods that are going to be called by the client
• The methods throws RemoteException
• Step Two: Create an implementation of the interface created in step one
• This implementation class must be a subclass of UnicastRemoteObject and must implement
the interface of step one
• All the methods specified in the interface must be implemented
• Should have at least a default constructor that throws RemoteException
• Step Three: Create a class containing the main method
• In the main method
• Create an object of the implementation of step one
• Register this object into the rmi registry of the server
• Step Four: Create the client
• Copy the interface defined in step one and put it in the folder where the client application is
saved
• Create a class containing the main method – and in the main method do the following
• Declare a reference variable of the interface defined in step one
• Search for the registered object
• Assign the search result to the reference variable created

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 13


Networking in Java – Remote Method Invocation
• To run and test the application
• Compile all the files
• Then, being on the server directory, start the rmi registry of the server using
the following command
• start rmiregistry
• Run the server
• Then run the client
• The interface
import java.rmi.*; //Remote and RemoteException classes
public interface ServerInterface extends Remote{
public double add(double x, double y) throws RemoteException;
}
Wednesday, May 29, 2024 By Melese E., Department of Computer Science 14
Networking in Java – Remote Method Invocation
• The implementation of the interface
import java.rmi.*;//RemoteException
import java.rmi.server.*;//UnicastRemoteObject
public class ServerImplementation extends UnicastRemoteObject implements ServerInterface{
public ServerImplementation() throws RemoteException{

}
public double add(double x, double y) throws RemoteException{
return x + y;
}
}

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 15


Networking in Java – Remote Method Invocation
• The Server Application
import java.rmi.*;//Naming and RemoteException
import java.net.*; //for MalformedURLException
public class ServerMain {
public static void main(String[] args) {
try{
ServerImplementation si = new ServerImplementation();
Naming.rebind("addition", si); // registering the object in the rmi registry
}catch(MalformedURLException e){

}catch(RemoteException e){

}
}
}

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 16


Networking in Java – Remote Method Invocation
• The Client Applciation
import java.rmi.*;//Naming, NotBoundException and RemoteException
import java.net.*;//MalformedURLException
public class RMIClient {
public static void main(String[] args){
String serverURL = "rmi://localhost/addition";
try{
ServerInterface si = (ServerInterface)Naming.lookup(serverURL);
double x = 55.5, y = 157.2;
double sum = si.add(x, y);
System.out.println("The sum is " + sum);
}catch(MalformedURLException e){
}
catch(NotBoundException e){
}
catch(RemoteException e){
}
}
}

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 17


The End!

Wednesday, May 29, 2024 By Melese E., Department of Computer Science 18

You might also like