Java Networking Basics
Download
Report
Transcript Java Networking Basics
Java Networking Basics
Introducing the Java Socket API
The socket API is an Inter-processing Communication (IPC) programming
interface originally provided as part of the Berkeley UNIX operating system.
It is a de facto standard for programming IPC, and is the basis of more
sophisticated IPC interface such remote method invocation.
Java provides the java.net and java.io packages as part of its API for network
programming.
Sockets represent the programmer’s connection to a communication channel
Exception handling and threads are also important to Java networking.
•
•
A socket API provides a programming
construct termed a socket. A process
wishing to communicate with another
process must create an instance of it
The two processes then issue operations
provided by the API to send and receive
data.
1
Java Networking Basics
Connection-oriented & Connectionless Socket
A socket programming construct can make use of either the UDP or TCP
protocol.
Sockets that use TCP are termed stream sockets.
Stream Sockets are inherently connection oriented.
Sockets that use UDP for transport are known as datagram sockets
Datagram sockets can support both connectionless and connectionoriented communication at the application layer.
This is so because even though datagrams are sent or received without the
notion of connections at the transport layer, the runtime support of the
socket API can create and maintain logical connections for datagrams
exchanged between two processes (see later).
2
Java Networking Basics
STREAM sockets
Bidirectional
Reliable
Sequenced (FIFO)
Unduplicated flow of data
No record boundaries - byte oriented
Connection oriented
Similar to the telephone
Uses TCP in the Internet domain
OutputStream
3..2..1..0
Communication Channel
InputStream
3..2..1..0
3
Java Networking Basics
DATAGRAM sockets
Bidirectional
May receive in different order (than sending)
May have duplicates
Record boundaries are preserved
Similar to mailing a letter
Uses UDP (User Datagram Protocol) in the Internet domain
UDP
Connectionless transport protocol that is packet based
Create a DatagramPacketObject (message + address)
Place on network for delivery
To receive packet, create a DatagramPacketObject and receive a UDP
packet into it.
4
Java Networking Basics
Connection-oriented & Connectionless Datagram Socket
socket
API runtime
support
Process A
Process B
socket
API runtime
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
API runtime
support
Process A
Process B
socket
API runtime
support
transport layer software
transport layer software
connection-oriented datagram socket
5
Java Networking Basics
The Java Package
The java.net provides the following networking classes
DatagramPacket
UDP Communication
DatagramSocket
InetAddress
ServerSocket
TCP Communication
Socket
URL
URLConnection
URLEncoder
URLStreamHandler
(Key classes are underlined)
For TCP java.net.Socket and ServerSocket
For UDP java.net.DatagramPacket and java.net.DatagramSocket
6
Java Networking Basics
TCP Networking
IP addresses, which are used to address the target of TCP connections are
provided by the InetAddress class.
TCP connections are created using the Socket class.
Once a connection has been created, we can create stream to/from the remote
application, and then communicate through the streams interface.
Other stream classes (e.g. filter stream class) can be used to add higher level
functions to this byte-oriented communication channel.
Building a TCP connection
Standard steps in building a TCP connection and using it are:
Get the server hostname or address
Get the service port number
Create a socket
Create input and output streams that use the socket
7
Java Networking Basics
java.net.Socket
Constructors for java.net.Socket:
•
Socket(String, int)
•
Socket(String, int, boolean)
•
Socket(InetAddress, int)
•
Socket(InetAddress, int, boolean)
Exceptions thrown by constructors:
•
UnknownHostException ,
•
IOException
java.net.Socket methods
•
getInetAddress()
•
getInputStream();
•
getOutputStream()
•
getLocalAddress();
•
getPort();
•
toString();
•
close();
8
Java Networking Basics
Domain Name Service (DNS)
Internet Protocol addresses are always numeric.
•
DNS is a service that translates between host names and IP addresses.
•
We generally don't use IP addresses(e.g. 130.191.143.100)
130.191.143.100 --> erne.research.edu
Java interface to DNS (the InetAddress class performs the lookups)
Methods:
String getHostName()
byte[] getAddress()
int hashCode()
boolean equals(Object)
String toString()
static InetAddress getByName(String)
static InetAddress[] getAllByName(String)
static InetAddress getLocalHost()
9
Java Networking Basics
Example use of InetAddress class
The following example prints the addresses and names of the local machine and
two well-known Internet web sites:
import java.net.*;
class InetAddressTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("starwave.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i = 0; i < SW.length; i++) {
System.out.println(SW[i]);
Here is the output produced by this program:
}
TOME6500/193.61.190.64
}
starwave.com/199.181.132.250
}
www.nba.com/88.221.87.167
www.nba.com/88.221.87.166
10
Java Networking Basics
TCP Simple Date/Time Client
This simple java program connects to a named server and can be used to read
the date and time from the designated port (i.e. port 13)
import java.net.Socket;
import java.io.InputStream;
public class SimpleTelnet
{
public static void main(String args[]) throws Exception
{
String serverName = args[0];
Argument (0) – server name
int portNumber = Integer.parseInt(args[1]);
Argument (1) – port number
Socket server = null;
Setting up connection socket to server
server = new Socket(serverName, portNumber);
InputStream input = server.getInputStream();
InputStreamReader inputText = new InputStreamReader(input);
Setting up a stream to read from
BufferedReader inputBuffer = new BufferedReader(inputText);
String message = inputBuffer.readLine(); This client only reads...
System.out.println("Received: " + message); We'll test it with a service that only writes,
}
namely the date/time facility on port 13.
}
JDK> java SimpleTelnet erne.research.edu 13
11
Received: Thu Feb 22 14:55:18 2014
Java Networking Basics
UDP Using Datagram socket API -1
In Java, two classes are provided for the datagram socket API:
A process wishing to send or receive data using this API must instantiate a
DatagramSocket object (or a socket in short).
the DatagramSocket class for the sockets.
the DatagramPacket class for holding the datagram
Each socket is said to be bound to a UDP port of the machine local to the process.
To send a datagram to another process, a process must:
Create an object that represents the datagram itself. This object can be
created by instantiating a DatagramPacket object which carries
(i) the payload data as a reference to a byte array, and
(ii) the destination address (the host ID and port number to which the
receiver’s socket is bound.
Issue a call to a send method in the DatagramSocket object, specifying a
reference to the DatagramPacket object as an argument.
12
Java Networking Basics
UDP Using Datagram socket API - 2
In the receiving process, a DatagramSocket object must also be instantiated and
bound to a local port;
The port number must agree with that specified in the datagram packet of the
sender.
To receive datagrams sent to the socket:
The process creates a DatagramPacket object which references a byte
array
Then calls a receive method in its DatagramSocket object, specifying as an
argument a reference to the DatagramPacket object.
The receive call in the DatagramSocket object will load the incoming
data into the DatagramPacket
The data (and address if needed) can then be extracted from the
DatagramPacket and processed as required.
13
Java Networking Basics
UDP The Data Structures in the sender and receiver Datagram programs
sender process
receiver process
a byte array
a byte array
receiver's
address
a DatagramPacket object
a DatagramPacket object
send
receive
a DatagramSocket
object
a DatagramSocket
object
object reference
data flow
14
Java Networking Basics
UDP The program flow in the sender and receiver programs
sender program
create a datagram socket and
bind it to any local port;
place data in a byte array;
create a datagram packet, specifying
the data array and the receiver's
address;
invoke the send method of the
socket with a reference to the
datagram packet;
receiver program
create a datagram socket and
bind it to a specific local port;
create a byte array for receiving the data;
create a datagram packet, specifying
the data array;
invoke the receive method of the
socket with a reference to the
datagram packet;
15
Java Networking Basics
Event Synchronization with Connectionless Datagram Socket API
server
client
receive
request
send
blocking receive,
nonblocking send
in a request-response
protocol
receive
blocked
response
send
if data is sent before a corresponding
receive operation is issued, the data will
be discarded by the runtime support
and will not be received.
16
Java Networking Basics
UDP Datagram Design Code
Read incoming message on port 2345
and print out its address and message
//Excerpt from a receiver program
DatagramSocket ds = new DatagramSocket(2345);
DatagramPacket dp =
new DatagramPacket(buffer, MAXLEN);
Receive Packet
ds.receive(dp);
Packet Length
len = dp.getLength( );
System.out.Println(len + " bytes received.\n");
String s = new String(dp.getData( ), 0, len);
System.out.println(dp.getAddress( ) + " at port "
+ dp.getPort( ) + " says " + s);
Send message “Hello World!” on
internal “localhost” loop to port
2345
// Excerpt from the sending process
InetAddress receiverHost=
InetAddress.getByName("localHost");
DatagramSocket theSocket = new DatagramSocket( );
String message = "Hello world!";
byte[ ] data = message.getBytes( );
data = theLine.getBytes( );
DatagramPacket thePacket
= new DatagramPacket(data, data.length,
receiverHost, 2345);
theSocket.send(theOutput);
Message Printed:
12 bytes received
Localhost at port 2345 says HelloWorld!
17
Java Networking Basics
UDP Connectionless Sockets
With connectionless sockets, it is possible for multiple processes to
simultaneously send datagrams to the same socket established by a receiving
process, in which case the order of the arrival of these messages will be
unpredictable, in accordance with the UDP protocol
Process B
Process A
Process B
Process A
Process C
Figure 3a
a connectionless
datagram socket
Process C
Figure 3b
18
Java Networking Basics
TCP Stream-mode Socket API (Client/Server Development)
In Java, the stream-mode socket API is provided with two classes to
facilitate client/server socket programming:
ServerSocket: for accepting connections:
we will call an object of this class a connection socket.
in the Java API this is a ServerSocket object
Socket: for data exchange:
we will call an object of this class a data socket.
in Java API this is a Socket object
java.net.ServerSocket
This class implements server sockets. A server socket waits for
requests to come in over the network. It performs some operation
based on that request, and then possibly returns a result to the
requester.
java.net.Socket
This class implements client sockets (also called just "sockets"). A
socket is an endpoint for communication between two machines.
19
Java Networking Basics
TCP Stream-mode Socket API Design Code
SERVER
Note. A “write” on the Client is matched by a
“read” on the Server (and vice versa)
CLIENT
Create a ConnectionSocket and listen for
connection requests;
Accept a connection;
Create a DataSocket for reading from or writing to
the Socket stream;
Create a DataSocket for writing to or
reading from and request connection;
Get an InputStream for reading from the
DataSocket;
Get an OutputStream for writing to the
DataSocket;
Read from the InputStream;
Write to the OutputStream;
Get an OutputStream for writing to the DataSocket;
Get an InputStream for reading from the
DataSocket;
Write to the OutputStream;
Read from the InputStream;
Close the DataSocket;
Close the ConnectionSocket;
Close the DataSocket;
20
Java Networking Basics
TCP Server (the connection listener)
A server uses two sockets: one for accepting connections, another for send/receive
client 1
server
connection
socket
connection operation
data socket
client 2
send/receive operaton
Note. In Java the “connection socket” is a ServerSocket and the “data socket” is a
Socket
21
Java Networking Basics
TCP Connection-oriented socket API Activity -1
client
server
1. Server establishes a
socket sd1 with local
address, then listens
for incoming
connection on sd1
2. Server accepts the
connection request
and creates a new
socket sd2 as a result.
sd1
Client establishes
a socket with
remote (server's)
address.
sd1
sd2
Note. In Java sd1 is a ServerSocket and sd2 is a Socket (sometimes called a DataSocket)
22
Java Networking Basics
TCP Connection-oriented socket API Activity -2
3. Server issues receive
operation using sd2.
sd1
Client issues
send operation.
sd2
4. Server sends response
using sd2.
sd1
sd2
5. When the protocol
has completed, server
closes sd2; sd1 is
used to accept the
next connection
sd1
Client closes its
socket when the
protocol has
completed
23
Java Networking Basics
UDP Connectionless socket API Activity
.
P1
P2
P1 establishes
a local socket
P2 establishes
a local socket
P1 issues a
receive operation
to receive the
datagram.
P2 sends a datagram
addressed to P1
Note. In Java these UDP sockets are all DatagramSockets
24
Java Networking Basics
Secure Sockets
Secure sockets perform encryption on the data transmitted.
The JavaTM Secure Socket Extension (JSSE) is a Java package that enables
secure Internet communications.
It implements a Java version of SSL (Secure Sockets Layer) and TLS
(Transport Layer Security) protocols
It includes functionalities for data encryption, server authentication, message
integrity, and optional client authentication.
Using JSSE, developers can provide for the secure passage of data between a
client and a server running any application protocol.
The Java Secure Socket Extension (JSSE) Reference Guide
http://download.java.net/jdk8/docs/technotes/guides/security/jsse/JSSERefGuide.html
25
Java Networking Basics
Summary
We have considered the conceptual model for the Java Socket API
UDP connectionless Datagram API
TCP connection oriented Socket stream API
Java Interface to DNS
Connection-oriented socket API Activity
Connectionless socket API Activity
Secure Sockets
26