Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Networking with Java

Daw Myat Aye Aye Aung


Assistant Lecturer

Faculty of Computer Science, University of Computer Studies, Yangon


Learning Outcomes

• To understand basic network terminology

• To be familiar with several common programming interfaces for network


communication

• To be able to implement client and server programs in Java using the


Sockets and Server sockets classes

Faculty of Computer Science, University of Computer Studies, Yangon 2


Basic of Networking
• Computers running on internet communicate to each other using either
the Transmission Control Protocol (TCP) or User Datagram Protocol
(UDP).

• Protocol is the special set of rules that end points in a telecommunication


connection use when they communicate.

Faculty of Computer Science, University of Computer Studies, Yangon 3


Client Server in Networking

• Involves two types of programs: client and server.


‒ Server : a program that provides services to one or more clients.
‒ Client : a program that makes a service request from server.

• Example:
World Wide Web  Server : Web Server
Client : Web Browsers

Faculty of Computer Science, University of Computer Studies, Yangon 4


TCP
• Like a telephone call

• Transmission Control Protocol (TCP) is connection-oriented.

• Guarantees that data sent from one end of the connection actually gets to
the other end in the same order it was sent.

• Works together with Internet Protocol (IP). TCP/IP makes a reliable


communication channel.
• Additional internet protocols:
‒ HTTP (Hypertext Transfer Protocol)
‒ FTP (File Transfer Protocol)
‒ Telnet
Faculty of Computer Science, University of Computer Studies, Yangon 5
UDP
• Like a postal service

• User Datagram Protocol (UDP) is a connectionless Internet protocol.

• It sends independent packets of data, called datagrams, from one


application to another.

• The order of delivery is not important and is not guaranteed, and each
message is independent of any other.

• Example
‒ Video conferencing, streaming, VoIP

Faculty of Computer Science, University of Computer Studies, Yangon 6


TCP vs. UDP

 Slower but reliable transfers  Fast but non-guaranteed transfers


 Typical applications: (“best effort”)
‒ Email  Typical applications:
‒ Web Browsing ‒ VoIP
‒ File Transfer Protocol (FTP) ‒ Live streaming
‒ Online games

unicast unicast multicast broadcast


Ref: https://microchipdeveloper.com/tcpip:tcp-vs-udp

Faculty of Computer Science, University of Computer Studies, Yangon 7


Internet Addressing
• Every computer on the internet has an address, called IP Address.
• This address is a number that uniquely identifies each computer on the
network.

Name Address
www.google.com 216.239.57.99
www.amazon.com 207.171.166.48

DNS ‒ Domain Name Server Name to Address Resolution is


done by DNS Server.

• DNS translates hostnames that humans can remember (like www.google.com) into
numeric Internet addresses (like 216.239.57.99).
Faculty of Computer Science, University of Computer Studies, Yangon 8
IP Address
• An Internet Protocol address (IP address) is a numerical label assigned to
each device (e.g., computer, printer) participating in a computer network.

• IP addresses are binary numbers, but they are usually stored in text files
and displayed in human-readable notations, such as 172.16.254.1 (for
IPv4), and 2001:db8:0:1234:0:567:8:1 (for IPv6).

Faculty of Computer Science, University of Computer Studies, Yangon 9


Port
• What is a port?
‒ A port is a virtual point where network connections start and end.
‒ A computer port is a type of electronic, software- or programming-related
docking point through which information flows from a program on your
computer or to your computer from the Internet or another computer in a
network.

• Ports are numbered for consistency and programming.

• Ports are represented by a 16-bit number (0 to 65535).

Faculty of Computer Science, University of Computer Studies, Yangon 10


Port (Cont’d)
• Port number < 1024 are reserved for special services.

• Port number >= 1024 are generally used for user level process or services.

• Example:
FTP  21
Telnet  23
SMTP  25
HTTP  80

Faculty of Computer Science, University of Computer Studies, Yangon 11


Some classes in java.net package
• Provides the classes for implementing networking applications.

import java.net.*; Java.net Package


InetAddress
Socket
ServerSocket
URI
URL
DatagramPacket
DatagramSocket
Faculty of Computer Science, University of Computer Studies, Yangon 12
InetAddress class
• Represents an IP address.

• Also provides methods to resolve host names to their IP addresses and


vice versa.

• The various address types are as follows:


 Unicast  sends IP packets to a single recipient on a network
 Multicast  sends IP packets to a group of hosts on a network

Faculty of Computer Science, University of Computer Studies, Yangon 13


Some methods of InetAddress Class
• String getHostAddress()
• String getHostName()
• static InetAddress getLocalHost()
• static InetAddress getByName(String host)
• static InetAddress[] getAllByName(String host)
• static InetAddress getByAddress(String host, byte[]
addr)
• boolean isLoopbackAddress()
• boolean isMulticastAddress()

Faculty of Computer Science, University of Computer Studies, Yangon 14


Example : InetAddress Class
import java.net.*;
public class InetAddressTest {
public static void main(String[] args)
{ String host = "www.google.com
"; try {
InetAddress address =
InetAddress.getByName(h
ost);
System.out.println(address);
InetAddress[ ] addresses = InetAddress.getAllByName(host);
www.google.com/74.125.24.106
for(InetAddress add:addresses) www.google.com/74.125.24.104
} catch (UnknownHostException e) { www.google.com/74.125.24.147
System.out.println(add);
e.printStackTrace(); } www.google.com/74.125.24.103
www.google.com/74.125.24.105
} www.google.com/74.125.24.99
} Faculty of Computer Science, University of Computer Studies, Yangon 15
Java Socket Programming

• Java socket programming is used for communication between the


applications running on the network.
‒ connection-oriented socket programming (TCP)

 Use Socket and ServerSocket classes


‒ connection-less socket programming (UDP)

 Use DatagramSocket and DatagramPacket classes

Faculty of Computer Science, University of Computer Studies, Yangon 16


Socket class
• Communication over the internet involves sockets for creating connections.

• Java supports sockets with the Socket class.

java.lang.object
java.net.Socket

• Some Constructors
‒ Socket()
‒ Socket(InetAddress address, int port)
‒ Socket(String host, int port)

Faculty of Computer Science, University of Computer Studies, Yangon 17


Some methods of Socket class
• void connect (SocketAddress
endpoint)
• void bind (SocketAddress
bindpoint)
• void close()
• boolean isBound()
• boolean isConnected()
• boolean isClosed()
• int getPort()

Faculty of Computer Science, University of Computer Studies, Yangon 18


Some methods of Socket class
• public InputStream getInputStream()
‒ returns the InputStream attached with this socket.

• public OutputStream getOutputStream()


‒ returns the OutputStream attached with this socket.
• public void close()
‒ closes this socket

Faculty of Computer Science, University of Computer Studies, Yangon 19


SeverSocket class
• Use to create a server application.

• Create object that is used to establish communication with the clients.

• Some Constructors
‒ ServerSocket()
‒ ServerSocket(int port)
‒ ServerSocket(int port, int maxQueue)
‒ ServerSocket(int port, int maxQueue, InetAddress localAddress)

Faculty of Computer Science, University of Computer Studies, Yangon 20


SeverSocket class (Cont’d)
• Some methods

 Socket accept()
 void bind(SocketAddress endpoint)
 void close()
 InetAddress getInetAddress()
 int getLocalPort()

Faculty of Computer Science, University of Computer Studies, Yangon 21


SeverSocket class (Cont’d)
• public Socket accept()
‒ returns the socket and establish a connection between server and client.

• public void close()


‒ closes the server socket.

Faculty of Computer Science, University of Computer Studies, Yangon 22


Socket Programming in Java
Creating Server Program
 need to create the instance of ServerSocket class
 ServerSocket svr_socket = new ServerSocket(port number);

ServerSocket svr_socket = new ServerSocket(9999);


Socket cli_socket = svr_socket.accept();//establishes connection and waits for client

Creating Client Program


 need to create the instance of Socket class
 Socket socket = new Socket(“server name”, port number);

Socket socket = new Socket("localhost",9999);

Faculty of Computer Science, University of Computer Studies, Yangon 23


Socket Programming in Java (Cont’d)
Read data from Client or Server

DataInputStream input = new DataInputStream (socket.getInputStream());


input.readInt();
input.readUTF();

Write data to Client or Server

DataOutputStream output =new DataOutputStream(socket.getOutputStream());


output.writeInt();
output.writeUTF();

Faculty of Computer Science, University of Computer Studies, Yangon 24


Read Data from Console

BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

Scanner scan = new Scanner (System.in);

Faculty of Computer Science, University of Computer Studies, Yangon 25


TCP/IP Client Sockets
• To receive response from the server:
Some useful classes to create input stream
• InputStream
- supports basic read( ) methods
• DataInputStream
- supports read( ), readChar( ), readInt( ), readDouble( ), etc.. methods
• InputStreamReader
- supports readLine( ) method
• BufferedReader
- supports readLine( ) method

Faculty of Computer Science, University of Computer Studies, Yangon 26


TCP/IP Client Sockets
• To send information to the server:
Some useful classes to create output stream
• OutputStream
- supports basic write( ) methods
• DataOutputStream
- supports print( ) methods to write Java primitive data types
• PrintStream
- supports print( ) methods for displaying Java primitive data types
• PrintWriter
- supports print( ) and println( ) methods

Faculty of Computer Science, University of Computer Studies, Yangon 27


Example 1
• Server Program
‒ Receives a text from client
‒ Prints it

• Client Program
‒ Send a text to server

Faculty of Computer Science, University of Computer Studies, Yangon 28


Example1: Server Program
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(9999);
System.out.println("Server is Ready");
Socket s = ss.accept();
System.out.println(“Connection is established");
DataInputStream din = new DataInputStream(s.getInputStream());
String str = din.readUTF();
System.out.println("message = "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
Faculty of Computer Science, University of Computer Studies, Yangon 29
Example1: Client Program
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",9999);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.close();
Output:
s.close();
}catch(Exception e){System.out.println(e);} Server is Ready
Connection is established
}
message = Hello Server
}

Faculty of Computer Science, University of Computer Studies, Yangon 30


Example 2: Calculator
• Server
‒ acts as a calculator
‒ accepts command and inputs, and calculates them
‒ return result

• Client
‒ interacts with user to get inputs
‒ request the server giving command with data
‒ receive the result

Faculty of Computer Science, University of Computer Studies, Yangon 31


Example 2: Server Program
import java.io.*;
import java.net.*;
public class CalculatorServer {
String cmd = "";
int num1 = 0;
int num2 = 0;
int result = 0;
public CalculatorServer() throws IOException {
ServerSocket svrSocket = new ServerSocket(1025);
System.out.println("Server is ready***");
Socket connSocket = svrSocket.accept();
System.out.println("Server and client is connected");

Faculty of Computer Science, University of Computer Studies, Yangon 32


Example 2: Server Program (Cont’d)
DataInputStream in = new DataInputStream(connSocket.getInputStream());
cmd = in.readUTF();
num1 = in.readInt();
num2 = in.readInt();

if (cmd.equalsIgnoreCase("ADD")) {
result =calculateSum(num1, num2);
} else if (cmd.equalsIgnoreCase("SUB")) {
result =calculateSub(num1, num2);
}

Faculty of Computer Science, University of Computer Studies, Yangon 33


Example 2: Server Program (Cont’d)
else if (cmd.equalsIgnoreCase("MULT")) {
result = calculateMultiply(num1, num2);
} else {
result = calculateDivide(num1, num2);
}
DataOutputStream out = new DataOutputStream(
connSocket.getOutputStream());
out.writeInt(result);
svrSocket.close();
}
private int calculateSum(int n1, int n2) {
return (n1 + n2);
}

Faculty of Computer Science, University of Computer Studies, Yangon 34


Example 2: Server Program (Cont’d)
private int calculateSub(int n1, int n2) {
return n1 - n2;
}
private int calculateMultiply(int n1, int n2) {
return n1 * n2;
}
private int calculateDivide(int n1, int n2) {
return n1 / n2;
}
public static void main(String[] args) throws IOException {
new CalculatorServer();
}
}

Faculty of Computer Science, University of Computer Studies, Yangon 35


Example 2: Client Program
import java.io.*;
import java.net.*;
public class CalculatorClient {
char ch;
public CalculatorClient() throws IOException,UnknownHostException{
Socket cliSocket = new Socket("localhost", 1025);

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));


System.out.println("Type a command ( ADD, SUB,MULT,DIV): ");
String cmd = br.readLine();

Faculty of Computer Science, University of Computer Studies, Yangon 36


Example 2: Client Program (Cont’d)
System.out.println("Enter number1 :");
int num1 = Integer.parseInt(br.readLine());

System.out.println("Enter number2 :");


int num2 = Integer.parseInt(br.readLine());

DataOutputStream out = new DataOutputStream(cliSocket.getOutputStream());

out.writeUTF(cmd);
out.writeInt(num1);
out.writeInt(num2);

Faculty of Computer Science, University of Computer Studies, Yangon 37


Example 2: Client Program (Cont’d)
// creating inputStream to read server reply
DataInputStream in = new DataInputStream(cliSocket.getInputStream());
int result = in.readInt();
System.out.println("Result = " + result);

cliSocket.close();
}
public static void main(String[] args) throws IOException {
new CalculatorClient();
}
}

Faculty of Computer Science, University of Computer Studies, Yangon 38


Exercise
• Write a client server program to calculate the Area and Perimeter of a
Square. Client accepts the length and sends it to the server. The server
calculates and returns the results. Client should display these results.

Faculty of Computer Science, University of Computer Studies, Yangon 39


Summary
• Java is a preferable language for network programming.

• java.net package encapsulate large number of classes and interface


which makes it easy to communicate via TCP/IP sockets or UDP sockets
over the internet.

Faculty of Computer Science, University of Computer Studies, Yangon 40

You might also like