3 - Module 2 - SocketProgramming

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

NETWORK PROGRAMMING

SOCKET PROGRAMMING
What is Networking
◼ When two processes lying on same or different
machines are communicating over the netword is
called networking
◼ For example: Client – server Communication

Request
Client Server
Response

◼ Process providing services is called Server


◼ Process consuming services is call Client

Khoa CNTT – ĐH Nông Lâm TP. HCM 2/78


Elements of Client – Server computing

Client
Server
Network

Client machine
Server machine
◼ There are four elements in networking:
◼ Client: sends request for servives
◼ Server: Sends (reply) response
◼ Network: media of communication
◼ Protocols: rules (language) for communication
Khoa CNTT – ĐH Nông Lâm TP. HCM 3/78
Single machine – Multiple clients
Google Microsoft Facebook
Server Server Server

Clients’ Machine
One machine can execute multiple clients processes concurrently
Khoa CNTT – ĐH Nông Lâm TP. HCM 4/78
Client is a Process
◼ One machine can run multiple clients (processes at a
time
◼ Client is not machine – it is a process:
◼ Web browser open google.com is a client
◼ Facebook messenger connected to chat server is a
client
◼ CuteFTP downloading a file from FTP server is a client
◼ All above mentioned clients (Browser, Messenger,
CuteFTP) run together on a single machine
concurrently

Khoa CNTT – ĐH Nông Lâm TP. HCM 5/78


Server is a Process too
◼ One machine can run multiple servers (processes at a
time
◼ Client is not machine – it is a process:
◼ Tomcate web server is a process
◼ Oracle database server is a process
◼ Apache web server is a process
◼ All above mentioned servers run together on a single
machine concurrently

Khoa CNTT – ĐH Nông Lâm TP. HCM 6/78


Single machine Multiple servers

Server Machine

Tomcat Web Server


(Port: 8080)

Apache Web Server


(Port: 80)

Oracle DB Server
(Port: 1521)

Khoa CNTT – ĐH Nông Lâm TP. HCM 7/78


How clients and Servers are identified
◼ Clients and Servers are uniquely identified on single
machine by unique port numbers
◼ Unique port number is assigned by OS
◼ Process can ask desired port number from OS
(typically server’s process) or OS will assign next
available port number to a process (typlically client’s
process)
◼ Port number is a two byte unsigned number ranging
from 0-65635

Khoa CNTT – ĐH Nông Lâm TP. HCM 8/78


Network Ports
◼ The TCP and UDP protocols use ports to map
incoming data to a particular process running on
a computer. P
o TCP
server
r Client
t

app app app app

port port port port


TCP or UDP
Packet
Data port# data

Khoa CNTT – ĐH Nông Lâm TP. HCM 9/78


Ports
◼ Port: a meeting place on a host
◼ one service per port
◼ 1-1023 = well-known services

◼ 1024+ = experimental services, temporary

Well-Known Ports:
◼ 20,21: FTP

◼ 23: Telnet
◼ 25: SMTP
◼ 80: HTTP
◼ 110: POP3
◼ 1099: RMI

Khoa CNTT – ĐH Nông Lâm TP. HCM 10/78


Ports

Khoa CNTT – ĐH Nông Lâm TP. HCM 11/78


Communication Rules (protocol)

Certain rules a followed when you communicate over


the network are called Protocols
Khoa CNTT – ĐH Nông Lâm TP. HCM 12/78
Protocol Stack on TCP/IP Model

Application Layer (HTTP, FTP, SMTP)

Transport Layer (TCP, UDP)

Internet Layer (IP)

Network Access Layer (Physical Network)

Khoa CNTT – ĐH Nông Lâm TP. HCM 13/78


Protocol Stack Communication

Khoa CNTT – ĐH Nông Lâm TP. HCM 14/78


TCP/UDP/IP
◼ IP
◼ raw packets
◼ the “Internet Layer”
◼ TCP
◼ data stream
◼ reliable, ordered
◼ the “Transport Layer”
◼ UDP
◼ user datagrams (packets)
◼ unreliable, unordered
◼ the “Transport Layer”
Khoa CNTT – ĐH Nông Lâm TP. HCM 15/78
Introduction to Socket API
◼ The socket API is an Interprocessing
Communication (IPC) programming
interface originally provided as part of the
Berkeley UNIX operating system.
◼ It has been ported to all modern operating
systems, including Sun Solaris and Windows
systems.
◼ It is a de facto standard for programming
IPC, and is the basis of more sophisticated IPC
interface such as remote procedure call and
remote method invocation.

Khoa CNTT – ĐH Nông Lâm TP. HCM 16/78


The conceptual model of the socket API
Process A Process B

Socket: two-way connection

a socket

Khoa CNTT – ĐH Nông Lâm TP. HCM 17/78


The socket API
◼ A socket API provides a programming
construct termed a socket. A process
wishing to communicate with another process
must create an instance, or instantiate, such a
construct
◼ The two processes then issues operations
provided by the API to send and receive data.
◼ Socket is a two-way connection

Khoa CNTT – ĐH Nông Lâm TP. HCM 18/78


TCP and UDP Socket
◼ A socket programming construct can make use of
either the UDP or TCP protocol.
◼ Sockets that use UDP for transport are known as
datagram sockets, while sockets that use TCP
are termed stream sockets.
◼ Datagram sockets can support both
connectionless and connection-oriented
communication at the application layer. The
runtime support of the socket API can create
and maintain logical connections for
datagrams exchanged between two
processes
Khoa CNTT – ĐH Nông Lâm TP. HCM 19/78
TCP and UDP Socket

socket socket
API runtime Process A Process B API runtime
support support

transport layer software transport layer software

connectionless datagram socket


a datagram
a logical connection created and maintained
by the runtime support of the datagram
socket API

socket socket
API runtime Process A Process B API runtime
support support

transport layer software transport layer software

connection-oriented datagram socket

Khoa CNTT – ĐH Nông Lâm TP. HCM 20/78


TCP and UDP Socket
◼ TCP
◼ When two applications want to communicate to each
other reliably, they establish a connection and send
data back and forth over that connection. HTTP,
FTP, Telnet are examples of applications that require
a reliable communication channel
◼ TCP provides a point-to-point channel for
applications that require reliable communications.
◼ UDP
◼ The UDP protocol provides for communication that
is not guaranteed between two applications on the
network. UDP is not connection-based like TCP.
Rather, it sends independent packets of data, called
datagrams, from one application to another
Khoa CNTT – ĐH Nông Lâm TP. HCM 21/78
Client - Server Comunication
Client Server
- initiate connection - Opens port and waits for
- Retrieve user input client
- Encapsulate in request and - Accept the next client
send it to the Server - Retrieve client request
- Retrieve data - Serve this request
(response) from Server - Encapsulate data in
- De-encapsulate and response
display data to users - Send response to client
- Request more data - Retrieve and serve more
- Request for closing requests
connection - Close connection

Khoa CNTT – ĐH Nông Lâm TP. HCM 22/78


Client - Server Comunication
◼ Difference between client and server is
semantic
◼ It’s all just peers talking to each other
◼ Protocol - roles, vocabulary, rules for
communication (more later)
Protocol

Client Server
- Client Task 1 initiates - Server Task 1
connection
- Client Task 2 - Server Task 2
- ..... - .....
- Client Task n Data Exchange - Server Task n
Khoa CNTT – ĐH Nông Lâm TP. HCM 23/78
Sockets and Ports (Diagram)

port 13 Time Service

Client Web Service


port 80

Socket Socket

Server

Khoa CNTT – ĐH Nông Lâm TP. HCM 24/78


Sockets and Ports

Local ports identify the application


establishing a connection from other
programs, allowing multiple TCP
applications to run on the same
machine.
Khoa CNTT – ĐH Nông Lâm TP. HCM 25/78
Transmission Control Protocol

1.

2.

3.

TCP establishes a virtual connection to transmit data

Khoa CNTT – ĐH Nông Lâm TP. HCM 26/78


TCP Socket API Model
Server
Client
ServerSocket()

bind(), listen()

accept()

Socket() TCP connection Block until connection


establishment from client

write() read()
Data (requests)

read() write()
Data (reply - response)

Close() Close()

Khoa CNTT – ĐH Nông Lâm TP. HCM 27/78


TCP Socket Programmning (1. step)
1a. ServerSocket server = new ServerSocket(port);
1b. Socket serverSoc = server.accept();

1c. Socket clientSoc = new Socket(serverAdd,port);

Khoa CNTT – ĐH Nông Lâm TP. HCM 28/78


TCP Socket Programmning (2. Step)
OutputStream outClient =
clientSoc.getOutputStream();
InputStream inServer =
serverSoc.getInputStream();
stream

Server Client

InputStream inClient =
clientSoc.getInputStream();
OutputStream outServer =
serverSoc.getOutputStream();
Khoa CNTT – ĐH Nông Lâm TP. HCM 29/78
TCP Socket Programmning (3. step)

3a. serverSoc.close();
3b. clientSoc.close();

◼ 3 steps in TCP Socket Programming:


◼ 1. Step: Connection establishment

◼ 2. Step: Client / server communication according to

protocol
◼ 3. Step: Connection closing

Khoa CNTT – ĐH Nông Lâm TP. HCM 30/78


Socket Basics
◼ A socket is a connection between two hosts. It can
perform seven basic operations:
1) Connect to a remote machine
2) Send data (request) Client:
3) Receive data (Response) Socket()
4) Close a connection

5) Bind to a port
6) Listen for incoming data Server:
7) Accept connections from ServerSocket()
remote machines on the
bound port

Khoa CNTT – ĐH Nông Lâm TP. HCM 31/78


Client socket

1. Open a socket.
2. Open an input stream and output stream to
the socket.
3. Read from and write to the stream according
to the server's protocol.(
4. Close the streams.
5. Close the socket.

Khoa CNTT – ĐH Nông Lâm TP. HCM 32/78


Client Socket - Constructors
◼ public Socket(String host, int port) throws
UnknownHostException, IOException
◼This constructor creates a TCP socket to the specified
port on the specified host and attempts to connect to
the remote host. For example:
try {
Socket toOReilly = new
Socket("www.oreilly.com", 80);
// send and receive data...
} catch (UnknownHostException e) { //IP
System.err.println(e);
} catch (IOException e) { //Port
System.err.println(e);
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 33/78


Socket Basics - Constructor
◼public Socket(InetAddress host, int port) throws
IOException
Create a TCP socket to the specified port on the specified host
and tries to connect by using an InetAddress object to specify the
host rather than a hostname.
try {
InetAddress OReilly =
InetAddress.getByName("www.oreilly.com");
Socket OReillySocket = new Socket(OReilly, 80);
// send and receive data...
}
//IP
catch (UnknownHostException e) { System.err.println(e);}
//Port
catch (IOException e) { System.err.println(e);}

Khoa CNTT – ĐH Nông Lâm TP. HCM 34/78


Client socket - LowPortScanner
import java.net.*;
import java.io.*;
public class LowPortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) host = args[0];
for (int i = 1; i < 1024; i++) {
try {
System.out.print("Scanning on port : "+i +" ; ");
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of "+host);
}
catch (UnknownHostException e) {
System.out.println("The Server adress is unknown");
break;
}
catch (IOException e) {
System.out.println("The Server is not found");
}
}}}

Khoa CNTT – ĐH Nông Lâm TP. HCM 35/78


Getting Information About a Socket
◼ public InetAddress getInetAddress( )
Given a Socket object, the getInetAddress( ) method tells
you which remote host the Socket is connected to or, if the
connection is now closed, which host the Socket was
connected to when it was connected. For example:

try {
Socket theSocket = new Socket("java.sun.com", 80);
InetAddress host = theSocket.getInetAddress( );
System.out.println("Connected to remote host " + host);
}
catch (UnknownHostException e) {System.err.println(e); }
catch (IOException e) {System.err.println(e); }

Khoa CNTT – ĐH Nông Lâm TP. HCM 36/78


Getting Information About a Socket
◼ public int getPort( )
The getPort( ) method tells you which port the Socket is (or was
or will be) connected to on the remote host. For example:
try {
Socket theSocket = new Socket("java.sun.com", 80);
int port = theSocket.getPort( );
System.out.println("Connected on remote port " + port);
}
◼ public int getLocalPort( )
There are two ends to a connection: the remote host and the
local host. To find the port number for the local end of a
connection, call getLocalPort( ). For example:
try {
Socket theSocket = new Socket("java.sun.com", 80, true);
int localPort = theSocket.getLocalPort( );
System.out.println("Connecting from local port " + localPort);
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 37/78
Client Socket – SocketInfo Program
public class SocketInfo {
public static void main(String[] args) {
String[] hostNames = {"www.hcmuaf.edu.vn",
"mail.hcmuaf.edu","testweb.hcmuaf.edu.vn"};
for (int i = 0; i< hostNames.length; i++){
try {
Socket theSocket = new Socket(hostNames[i], 80);
System.out.println("Connected to "+ theSocket.getInetAddress( )
+ " on port " + theSocket.getPort( ) + " from port "
+ theSocket.getLocalPort( ) + " of " +
theSocket.getLocalAddress( ));
}
catch (UnknownHostException e) {
System.err.println("I can't find " + hostNames[i]);
}
catch (SocketException e) {
System.err.println("Could not connect to " + hostNames[i]);
}
catch (IOException e) {
System.err.println(e);
}
}}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 38/78
Getting Information About a Socket
◼ public InputStream getInputStream( ) throws
IOException
◼The getInputStream( ) method returns an input
stream that can read data from the socket into a
program. You usually chain this InputStream to a
filter stream or reader that offers more functionality—
DataInputStream or InputStreamReader, for
example—before reading input. It's also extremely
helpful to buffer the input by chaining it to a
BufferedInputStream or a BufferedReader for
performance reasons
◼When reading data from the network, it's important to
keep in mind that not all protocols use ASCII or even
text.
Khoa CNTT – ĐH Nông Lâm TP. HCM 39/78
Getting Information About a Socket
◼ public OutputStream getOutputStream( ) throws
IOException
◼The getOutputStream( ) method returns a raw
OutputStream for writing data from your application to
the other end of the socket. You usually chain this
stream to a more convenient class like
DataOutputStream or OutputStreamWriter before
using it. For performance reasons, it's a good idea to
buffer it as well.
◼The following example uses getOutputStream( ) and
getInputStream( ) to implement a simple echo client.
The user types input on the command-line, which is
then sent to the server. The server echoes it back

Khoa CNTT – ĐH Nông Lâm TP. HCM 40/78


From FileCopy to NetCopy
◼ OPEN source file
◼ CREATE destination file
◼ REPEAT more data (is not end of source file)
◼ Read data from source file
◼ Write data into destination file
◼ END REPEAT
◼ CLOSE source file
◼ CLOSE dest. file

Khoa CNTT – ĐH Nông Lâm TP. HCM 41/78


Client Socket - An Echo Client
import java.net.*;
import java.io.*;
public class EchoClient {
public static final int ECHO_PORT = 7;
public static void main(String[] args) {
String hostname = "localhost";

PrintWriter out = null;


BufferedReader networkIn = null;
try {
Socket theSocket = new Socket(hostname, ECHO_PORT);
networkIn = new BufferedReader(
new InputStreamReader(theSocket.getInputStream()));
out = new PrintWriter(theSocket.getOutputStream());
BufferedReader userIn = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("Connected to echo server");


System.out.println(networkIn.readLine());
Khoa CNTT – ĐH Nông Lâm TP. HCM 42/78
Client Socket - An Echo Client
while (true) {
String theLine = userIn.readLine();
out.println(theLine); out.flush();
System.out.println(networkIn.readLine());
if (theLine.equals("BYE")) break;
}
} // end try
catch (IOException e) {
System.err.println(e);
}
finally {
try {
if (networkIn != null) networkIn.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
} // end main
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 43/78
Client Socket - Closing the Socket
◼ public synchronized void close( ) throws
IOException
◼ When you're through with a socket, you should call its
close( ) method to disconnect. Ideally, you put this in a
finally block so that the socket is closed whether or not an
exception is thrown.
Socket connection = null;
try {
Socket connection = new Socket("www.oreilly.com", 13);
// interact with the socket
} // end try
catch (UnknownHostException e) { System.err.println(e); }
catch (IOException e) {System.err.println(e);}
finally {
if (connection != null) connection.close( );
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 44/78
Program using server socket
1) Create a ServerSocket, specifying a port to listen on.
2) Invoke the ServerSocket's accept() method to listen
on the configured port for a client connection.
3) When a client connects to the server, the accept()
method returns a Socket through which the server
can communicate with the client: Obtain an
InputStream to read from the client and an
OutputStream write to the client.
4) Pass the Socket to another thread to process so that
your server can continue listening for additional
connections.
5) Call the ServerSocket's accept() method again to
listen for another connection.
Khoa CNTT – ĐH Nông Lâm TP. HCM 45/78
ServerSocket - Sockets for Servers
◼ public ServerSocket(int port) throws IOException,
BindException
◼ This constructor creates a server socket on the port specified by
the argument.
◼ For example, to create a server socket that would be used by an
HTTP server on port 80, you would write:
try {
ServerSocket httpd = new ServerSocket(80);
} catch (IOException e) { System.err.println(e); }
◼ The constructor throws an IOException (specifically, a
BindException) if the socket cannot be created and bound to the
requested port.
◼ An IOException when creating a ServerSocket almost always
means one of two things. Either another server socket is
already using the requested port, or you're trying to connect
to a port from 1 to 1023 on Unix without root (superuser)
privileges.
Khoa CNTT – ĐH Nông Lâm TP. HCM 46/78
ServerSocket - LocalServerPortScanner
import java.net.*;
import java.io.*;

public class LocalServerPortScanner {


public static void main(String[] args) {
for (int port = 1; port <= 1024; port++) {
try {
// the next line will fail and drop into the catch block if
// there is already a server running on the port
ServerSocket server = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("There is a server on port " +
port + ".");
} // end try
} // end for
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 47/78
ServerSocket - Sockets for Servers
◼ public Socket accept( ) throws IOException
This method "blocks": it stops the flow of execution and
waits until a client connects. When a client does connect,
the accept( ) method returns a Socket object. You use the
streams returned by this Socket's getInputStream( ) and
getOutputStream( ) methods to communicate with the client. For
example:

ServerSocket server = new ServerSocket(5776);


while (true) {
Socket connection = server.accept( );
PrintWriter out
= new PrintWriter(connection.getOutputStream( ),TRUE);
out. println("You've connected to this server. Bye-bye now.");
connection.close( );
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 48/78
ServerSocket - Socket Options
◼ The only socket option supported for server sockets is
SO_TIMEOUT. SO_TIMEOUT is the amount of time, in
milliseconds, that accept( ) waits for an incoming
connection before throwing a InterruptedIOException. If
SO_TIMEOUT is 0, then accept( ) will never time out. The
default is to never time out.
◼ public void setSoTimeout(int timeout) throws
SocketException
◼ The setSoTimeout() method sets the SO_TIMEOUT field for
this server socket object. The countdown starts when
accept() is invoked. When the timeout expires, accept()
throws an InterruptedIOException. You should set this
option before calling accept(); you cannot change the
timeout value while accept() is waiting for a connection.
The timeout argument must be greater than or equal to
zero;
Khoa CNTT – ĐH Nông Lâm TP. HCM 49/78
ServerSocket - Socket Options
try {
ServerSocket server = new ServerSocket(2048);
// block for no more than 30 seconds
server.setSoTimeout(30000);
try {
Socket s = server.accept();
// handle the connection
// ...
}
catch (InterruptedIOException e) {
System.err.println("No connection within 30 seconds");
}
finally {
server.close( );
}
catch (IOException e) {
System.err.println("Unexpected IOException:" + e);
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 50/78
ServerSocket – EchoServer Implement
public class EchoServer {
public static final int ECHO_PORT = 7;
public static void main(String[] args) {
try {
// establish server socket
ServerSocket s = new ServerSocket(ECHO_PORT);
// wait for client connection
Socket incoming = s.accept();
BufferedReader in = new BufferedReader (new
InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);

out.println("Welcome to ECHO SERVER! Enter BYE to


exit.");

Khoa CNTT – ĐH Nông Lâm TP. HCM 51/78


ServerSocket – EchoServer Implement
// echo client input
boolean done = false;
while (!done) {
String line = in.readLine();
if (line == null) done = true;
else {
out.println("Echo: " + line);
if (line.trim().equals("BYE"))
done = true;
}
}
incoming.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 52/78
ServerSocket – EchoServer Implement
public class ThreadedEchoServer {
public static final int ECHO_PORT = 7;
public static void main(String[] args) {
try {
int i = 1;
ServerSocket s = new ServerSocket(ECHO_PORT);
for (; ; ) {
Socket incoming = s.accept();
System.out.println("Connection number:" + i);
System.out.println("Local Port: "+ incoming.getLocalPort()+
"Foreign Port :"+ incoming.getPort());
Thread t = new ThreadedEchoHandler(incoming, i);
t.start(); i++;
}
}
catch (Exception e) {
e.printStackTrace();
}}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 53/78
ServerSocket - ThreadedEchoServer
class ThreadedEchoHandler extends Thread {
private Socket incoming;
private int counter;
public ThreadedEchoHandler(Socket i, int c) {
incoming = i;
counter = c;
}
public void run() {
try {
BufferedReader in = new BufferedReader (new
InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter (incoming.getOutputStream(), true);
out.println("Welcom to Threaded ECHO SERVER! Enter BYE to exit.");
boolean done = false;
while (!done) {
String str = in.readLine();
if (str == null) done = true;
else {
out.println("Echo (" + counter + "): " + str);
if (str.trim().equals("BYE")) done = true;
}}
incoming.close();
}
catch (Exception e) {
e.printStackTrace();
}}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 54/78
Socket Basics - Half-closed sockets
◼ When a client program sends a request to the server, the
server needs to be able to determine when the end of the
request occurs. For that reason, many Internet protocols
(such as SMTP) are line-oriented. Other protocols
contain a header that specifies the size of the request data.
Otherwise, indicating the end of the request data is harder
than writing data to a file. With a file, you'd just close the
file at the end of the data. But if you close a socket, then
you immediately disconnect from the server.
◼ The half-close overcomes this problem. You can close the
output stream of a socket, thereby indicating to the server
the end of the request data, but keep the input stream
open so that you can read the response.
◼ public void shutdownInput( ) throws IOException
◼ public void shutdownOutput( ) throws IOException

Khoa CNTT – ĐH Nông Lâm TP. HCM 55/78


Socket Basics - Half-closed sockets
Socket connection = null;
try {
connection = new Socket("www.oreilly.com", 80);
BufferedReader reader = new BufferedReader( new
InputStreamReader(socket.getInputStream()));
Writer out = new OutputStreamWriter(connection.getOutputStream( ),
“UTF-8");
out.write("GET / HTTP 1.0\r\n\r\n");
out.flush( );
connection.shutdownOutput( );
// now socket is half closed; read response data
String line;
while ((line = reader.readLine()) != null)
...
} catch (IOException e) {}
finally {
try {
if (connection != null) connection.close( );
} catch (IOException e) {}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 56/78


InetAddress class
◼ Usually, you don't have to worry too much about Internet
addresses—the numerical host addresses that consist of
four bytes such as 132.163.4.102. However, you can use
the InetAddress class if you need to convert between host
names and Internet addresses.
◼ The static getByName method returns an InetAddress
object of a host.
◼ For example,
InetAddress address =
InetAddress.getByName("time-A.timefreq.bldrdoc.gov");
◼ returns an InetAddress object that encapsulates the
sequence of four bytes 132.163.4.102. You can access the
bytes with the getAddress method.
◼ byte[] addressBytes = address.getAddress();

Khoa CNTT – ĐH Nông Lâm TP. HCM 57/78


InetAddress class
◼ Some host names with a lot of traffic correspond to
multiple Internet addresses, to
◼ facilitate load balancing. You can get all hosts with the
getAllByName method.
◼ InetAddress[] addresses =
InetAddress.getAllByName(host);
◼ Finally, you sometimes need the address of the local
host. If you simply ask for the address of localhost, you
always get the address 127.0.0.1, which isn't very
useful. Instead, use the static getLocalHost method to
get the address of your local host.
◼ InetAddress address = InetAddress.getLocalHost();

Khoa CNTT – ĐH Nông Lâm TP. HCM 58/78


InetAddress class
◼ public String getHostName()
Gets the host name for this IP address. If this
InetAddress was created with a host name, this host
name will be remembered and returned; otherwise, a
reverse name lookup will be performed and the result will
be returned based on the system configured name lookup
service.
◼ public String getCanonicalHostName()
Gets the fully qualified domain name for this IP address.
Best effort method, meaning we may not be able to
return the FQDN depending on the underlying system
configuration.
◼ public byte[] getAddress()

Returns the raw IP address of this InetAddress object.


The result is in network byte order: the highest order
byte of the address is in getAddress()[0].
Khoa CNTT – ĐH Nông Lâm TP. HCM 59/78
InetAddress class
◼ public String getHostAddress()
Returns the IP address string in textual presentation for
example "132.163.4.102".
◼ public String toString()
Converts this IP address to a String. The string returned is of
the form: hostname / literal IP address. If the host name is
unresolved, no reverse name service loopup is performed.
The hostname part will be represented by an empty string.
◼ public static InetAddress getByName(String host)
throws UnknownHostException
Determines the IP address of a host, given the host's name.
The host name can either be a machine name, such as
"java.sun.com", or a textual representation of its IP address.

Khoa CNTT – ĐH Nông Lâm TP. HCM 60/78


InetAddress class
◼ public static InetAddress[] getAllByName(String host)
throws UnknownHostException
Given the name of a host, returns an array of its IP
addresses, based on the configured name service on the
system. The host name can either be a machine name, such
as "java.sun.com", or a textual representation of its IP
address.
◼ public static InetAddress getByAddress(byte[] addr)
throws UnknownHostException
Returns an InetAddress object given the raw IP address . The
argument is in network byte order: the highest order byte of
the address is in getAddress()[0].
◼ public static InetAddress getLocalHost() throws
UnknownHostException
Returns the local host.

Khoa CNTT – ĐH Nông Lâm TP. HCM 61/78


InetAddress example - NSLookup
public class NSLookup {
public static void main(String[] args) {
String hostName = "localhost";
String hostNameIP = "127.0.0.1";
InetAddress add;
try{
add = InetAddress.getByName(hostName);
System.out.println("DNS host name: "+add.getCanonicalHostName());
System.out.println("IP Address: "+add.getHostAddress());

add = InetAddress.getByName(hostNameIP);
System.out.println("DNS host name: "+add.getCanonicalHostName());
System.out.println("IP Address: "+add.getHostAddress());
System.out.println("InetAddress toString: "+add);

InetAddress[] addresses = InetAddress.getAllByName(hostName);


for (int i = 0; i < addresses.length; i++)
System.out.println(addresses[i]);
} catch(UnknownHostException e){
System.out.println("The Address not exist"); }
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 62/78
UDP Programming
UDP Advantages
◼ Less overhead (no connection establishment)
◼ More efficient (no guaranteed delivery)
◼ Real-time applications (no error checking or
flow-control): weather, time, video, audio,
games
◼ Data reception from more than one machine

Khoa CNTT – ĐH Nông Lâm TP. HCM 64/78


Overview

Khoa CNTT – ĐH Nông Lâm TP. HCM 65/78


Basic of UDP Programming
◼ Java DatagramSocket and DatagramPacket classes are
used for connection-less (UDP) socket programming
◼ Java DatagramSocket class represents a
connection-less socket for sending and receiving
datagram packets. It is a mechanism used for
transmitting datagram packets over network
◼ Java DatagramPacket is a message that can be
sent or received. It is a data container. If you send
multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed

Khoa CNTT – ĐH Nông Lâm TP. HCM 66/78


UDP Sender / Receiver model
UDP Sender
DatagramPacket B B B B
DatagramSocket
B B B B Data
Byte array
send() B B B B
Sender:
Construct a DatagramPacket B B B B
Packet B B B B

Packet Receiver: UDP Receiver


Read from a DatagramPacket
receive() Data
B B B B
B B B B
DatagramPacket
DatagramSocket
B B B B B B B B
Byte array
B B B B

Khoa CNTT – ĐH Nông Lâm TP. HCM 67/78


DatagramPacket Class
is a wrapper for an array of bytes from which data will be
sentor into which data will be received. It also contains the
address and port to which the packet will be sent.

Port (Remote Port)


DataPacket(port)
…setPort(port)

Khoa CNTT – ĐH Nông Lâm TP. HCM 68/78


DatagramPacket - Constructors
◼ DatagramPacket(byte[] barr, int length)
◼ creates a datagram packet. This constructor is used

to receive the packets.


◼ DatagramPacket(byte[] barr, int length,
InetAddress address, int port)
◼ creates a datagram packet. This constructor is used

to send the packets.

Khoa CNTT – ĐH Nông Lâm TP. HCM 69/78


Creating a UDP DatagramPacket
1. to receive data from a remote machine
◼ DatagramPacket(byte[] buffer, int length)

◼ DatagramPacket packet =

new DatagramPacket(new byte[256], 256);


2. to send data to a remote machine
◼ DatagramPacket(byte[] buffer, int length,

InetAddress dest_addr, int dest_port)


◼ DatagramPacket packet = new DatagramPacket(new
byte[128], 128, address, port );

Khoa CNTT – ĐH Nông Lâm TP. HCM 70/78


DatagramPacket
◼ void setAddress(InetAddress addr)— assigns a
new destination address to a DatagramPacket.
◼ void setData(byte[] buffer)— assigns a new data
buffer to the DatagramPacket. Remember to make the
buffer long enough, to prevent data loss.
◼ void setLength(int length)— assigns a new length
to the DatagramPacket. Remember that the length
must be less than or equal to the maximum size of the
data buffer, or an IllegalArgumentException will be
thrown. When sending a smaller amount of data, you
can adjust the length to fit—you do not need to resize
the data buffer.
◼ void setPort(int port)— assigns a new destination
port to a DatagramPacket.

Khoa CNTT – ĐH Nông Lâm TP. HCM 71/78


DatagramPacket
◼ InetAddress getAddress()— returns the IP address
from which a DatagramPacket was sent, or (if the
packet is going to be sent to a remote machine), the
destination IP address.
◼ byte[] getData()— returns the contents of the
DatagramPacket, represented as an array of bytes.
◼ int getLength()— returns the length of the data
stored in a DatagramPacket. This can be less than the
actual size of the data buffer.
◼ int getPort()— returns the port number from which a
DatagramPacket was sent,or (if the packet is going to
be sent to a remote machine), the destination port
number.

Khoa CNTT – ĐH Nông Lâm TP. HCM 72/78


DatagramSocket Class
◼ The DatagramSocket class provides access to a UDP
socket, which allows UDP packets to be sent and
received.
◼ The same DatagramSocket can be used to receive
packets as well as to send them. However, read
operations are blocking, meaning that the application will
continue to wait until a packet arrives.
◼ A DatagramSocket can be used to both send and receive
packets. Each DatagramSocket binds to a port on the
local machine, which is used for addressing packets. The
application is a UDP server, it will usually choose a
specific port number. If the DatagramSocket is intended
to be a client, and doesn't need to bind to a specific port
number, a blank constructor can be specified.

Khoa CNTT – ĐH Nông Lâm TP. HCM 73/78


DatagramSocket
◼ public DatagramSocket() throws SocketException
Constructs a datagram socket and binds it to any
available port on the local host machine.
◼ public DatagramSocket(int port) throws
SocketException
Constructs a datagram socket and binds it to the
specified port on the local host machine
◼ public void close()
closes a socket, and unbinds it from the local port.

Khoa CNTT – ĐH Nông Lâm TP. HCM 74/78


Creating a DatagramSocket
1. Create datagram socket on Client:
◼ public DatagramSocket() throws SocketException

◼ DatagramSocket clientSocket =

new DatagramSocket();

2. Create datagram socket on Server:


◼ public DatagramSocket(int port) throws
SocketException
◼ DatagramSocket serverSocket =

new DatagramSocket(port);

Khoa CNTT – ĐH Nông Lâm TP. HCM 75/78


DatagramSocket API
◼ void receive(DatagramPacket packet) throws
java.io.IOException — reads a UDP packet and
stores the contents in the specified packet. The
address and port fields of the packet will be overwritten
with the sender address and port fields, and the length
field of the packet will contain the length of the original
packet, which can be less than the size of the packet's
byte-array. If a timeout value has been specified, a
java.io.InterruptedIOException will be thrown if the
time is exceeded.
◼ void send(DatagramPacket packet) throws
java.io.IOException— sends a UDP packet,
represented by the specified packet parameter.

Khoa CNTT – ĐH Nông Lâm TP. HCM 76/78


DatagramSocket API
◼ InetAddress getInetAddress() — Returns the address
to which this socket is connected.
◼ int getPort() — returns the remote port to which the
socket is connected, or –1 if no such connection exists.
◼ InetAddress getLocalAddress()— returns the local
address to which the socket is bound.
◼ int getLocalPort()— returns the local port to which the
socket is bound.
◼ int getReceiveBufferSize() throws
java.net.SocketException— returns the maximum buffer
size used for incoming UDP packets.
◼ int getSendBufferSize() throws
java.net.SocketException— returns the maximum buffer
size used for outgoing UDP packets.

Khoa CNTT – ĐH Nông Lâm TP. HCM 77/78


DatagramSocket API
◼ void setReceiveBufferSize(int length) throws
java.net.SocketException— sets the maximum buffer
size used for incoming UDP packets. Whether the
specified length will be adhered to is dependent on the
operating system.
◼ void setSendBufferSize(int length) throws
java.net.SocketException— sets the maximum buffer
size used for outgoing UDP packets. Whether the
specified length will be adhered to is dependent on the
operating system.
◼ void setSoTimeout(int duration) throws
java.net.SocketException— sets the value of the
timeout socket option. This value is the number of
milliseconds a read operation will block before throwing
a java.io.InterruptedIOException.

Khoa CNTT – ĐH Nông Lâm TP. HCM 78/78


Receiving UDP Packets

▪ UDP packets are received by a DatagramSocket


and translated into a DatagramPacket object.
▪ When an application wishes to read UDP packets, it
calls the DatagramSocket.receive method, which
copies a UDP packet into the specified
DatagramPacket. The contents of the
DatagramPacket are processed, and the process is
repeated as needed.
Khoa CNTT – ĐH Nông Lâm TP. HCM 79/78
Listening for UDP Packets
// create datagram packet
DatagramPacket packet = new DatagramPacket (new
byte[256], 256);

// create datagram server socket


DatagramSocket socket = new DatagramSocket(2000);

boolean finished = false;


while (! finished ){
socket.receive (packet);
// process the packet
}

socket.close();

Khoa CNTT – ĐH Nông Lâm TP. HCM 80/78


Processing UDP Packets

ByteArrayInputStream bin = new


ByteArrayInputStream(packet.getData() );
DataInputStream din = new DataInputStream (bin);
// Read the contents of the UDP packet
.......
Khoa CNTT – ĐH Nông Lâm TP. HCM 81/78
Sending UDP packets

Khoa CNTT – ĐH Nông Lâm TP. HCM 82/78


Sending UDP packets
// create datagram client socket
DatagramSocket socket = new DatagramSocket();
// create datagram packet
DatagramPacket packet = new DatagramPacket (new byte[1], 1);
packet.setAddress (InetAddress.getByName (someServer));
packet.setPort (2000);
boolean finished = false;
while !finished ){
// Write data to packet buffer
.........
packet.setData(…..);
packet.setLength(…);
socket.send (packet);
// Do something else, like read other packets, or check to
// see if no more packets to send
.........
}
socket.close();
Khoa CNTT – ĐH Nông Lâm TP. HCM 83/78
UDP: EchoServer
byte[] buff = new byte[256];
int serverPort = 7;
DatagramSocket socket = new
DatagramSocket(serverPort);
DatagramPacket packet = new DatagramPacket(buff,
buff.length);
while (true) {
packet.setData(buff);
packet.setLength(buff.length);
socket.receive(packet);
String received = new String(packet.getData(),
0, packet.getLength());

Khoa CNTT – ĐH Nông Lâm TP. HCM 84/78


UDP: EchoServer
if (received.equals("end")) {
break;
}
received = "Echo:" + received;
byte[] data = received.getBytes();
packet.setData(data);
packet.setLength(data.length);
socket.send(packet);
}
socket.close();

Khoa CNTT – ĐH Nông Lâm TP. HCM 85/78


UDP: EchoClient
DatagramSocket socket;
InetAddress address;
int serverPort = 7;
byte[] buff = new byte[256];

socket = new DatagramSocket();


address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buff,
buff.length, address, serverPort);

BufferedReader userIn = new BufferedReader(new


InputStreamReader(System.in));
String line;
while ((line = userIn.readLine())!=null) {
byte[] data = line.getBytes();
Khoa CNTT – ĐH Nông Lâm TP. HCM 86/78
UDP: EchoClient
byte[] data = line.getBytes();
packet.setData(data);
packet.setLength(data.length);
socket.send(packet);

if (line.equals("end")) break;

packet.setData(buff);
packet.setLength(buff.length);
socket.receive(packet);
String received = new String(packet.getData(),
0, packet.getLength());
System.out.println(received);
}//while
socket.close();

Khoa CNTT – ĐH Nông Lâm TP. HCM 87/78

You might also like