2. Networking
● Java provides cross-platform networking facilities
●
java.net and javax.net packages contain many useful classes
● API is generally protocol independent, but implementation supports
mostly Internet transport protocols, e.g. TCP and UDP
● java.net.InetAddress represents an IP address (immutable)
– Inet4Address represents 32-bit IPv4 addresses (4 billions)
– Inet6Address represents 128-bit IPv6 addresses (3.4 x 10 38)
– It is able to detect address types, provides naming services, and
various other checks and conversions
– Create using InetAddress.getByAddress(...), getByName(...)
or getLocalHost()
– Many getXXX() and isXXX() methods provided
Java course – IAG0040 Lecture 9
Anton Keks Slide 2
3. Sockets
● Sockets are used as endpoints in network communication
●
java.net.InetSocketAddress represents an address-port pair
● There are several types of sockets in Java
– Socket and ServerSocket – connection-oriented streaming reliable client
and server sockets (TCP)
– SSLSocket and SSLServerSocket – client and server sockets for secure
encrypted communication (TCP via SSL)
– DatagramSocket – packet-oriented unreliable socket for both sending and
receiving data (UDP), can be used for both unicasting and broadcasting
– MulticastSocket – datagram socket with multicasting support
● Socket implementations depend on respective factory classes. Direct
usage uses the default socket factory for the given socket type.
Java course – IAG0040 Lecture 9
Anton Keks Slide 3
4. Networking Exceptions
●
Most networking exceptions extend
SocketException
● SocketException extends IOException, showing
that networking is highly related to all other
more generic I/O classes
Java course – IAG0040 Lecture 9
Anton Keks Slide 4
5. Streaming Sockets
● Socket and ServerSocket can be used for streaming
● Underlying Socket implementations are provided by
SocketImplFactory classes by the means of SocketImpl classes.
Default implementation is plain TCP.
● getInputStream() and getOutputStream() are used for
obtaining the streams, both can be used simultaneously
● Various socket options may be set using provided set methods
● There are many informative is/get methods provided
● Stream sockets must be closed using the close() method
– it closes both streams automatically as well
Java course – IAG0040 Lecture 9
Anton Keks Slide 5
6. Datagram Sockets
●
DatagramSocket is used for sending and receiving of
DatagramPackets; receiving is actually 'listening'
●
Connection-less, no streams provided
● connect() and disconnect() is used for
selecting/resetting the remote party's address and port
●
Special addresses can be used for sending/receiving of
broadcast packets, e.g. 192.168.0.255
●
MulticastSocket can be used for joining/leaving multicast
groups of DatagramSockets. Multicast groups have special
addresses.
Java course – IAG0040 Lecture 9
Anton Keks Slide 6
7. URL and URLConnection
●
Java also provides higher-level networking APIs than Sockets
●
URI and URL classes provide construction and parsing of the
respective Strings (all URLs are URIs, however)
– URI is a newer class and provides encoding/decoding of
escaped symbols, like %20
– Conversions back and forth are possible using toURI()
and toURL() methods
●
URLConnection provides API for reading/writing of the
resources referenced by URLs
● url.openConnection() returns a subclass of
URLConnection, according to the registered protocol-specific
URLStreamHandler
Lecture 9
Slide 7
8. URL and URLConnection (cont)
● Obtained URLConnection can be used for setting various
parameters (headers)
– Actual connection is opened using the connect() method
– Both getInputStream() and getOutputStream() are
provided
– getContent() returns an Object according to the MIME
type of the resource, which ContentHandler is provided by
the ContentHandlerFactory
● url.openStream() is a shortcut if you need to just retrieve
the data without any extra features
●
Proxy/ProxySelector can be used for proxying of traffic
Lecture 9
Slide 8
9. Networking Task
●
Implement the FileDownloader (eg using existing
DataCopier implementation)
●
Try your code with various Input and Output streams
– Files, Sockets, URLs
●
Create FileSender and FileReceiveServer classes. Reuse
already written code to send file content over the socket
and save content to another file on the server end
Lecture 9
Slide 9
10. Reflection API
● The reflection API represents, or reflects, the
classes, interfaces, and objects in the current
JVM
– It is possible to dynamically collect information about
all aspects of compiled entities, even access private
fields
● Reflection API is in java.lang and
java.lang.reflect packages
● Note: Reflection API is also full of generics
(for convenience)
Java course – IAG0040 Lecture 9
Anton Keks Slide 10
11. Reflection API usage
●
Where is it appropriate to use it?
– various plugins and extensions: load classes by
name, etc
– JUnit uses reflection for finding test methods
either by name or annotations
– Many other famous frameworks use reflection, e.g.
Hibernate, Spring, Struts, Log4J, JUnit, etc
●
Caution: use reflection only when it is absolutely
necessary!
Java course – IAG0040 Lecture 9
Anton Keks Slide 11
12. Examining Classes
●
Class objects reflect Java classes
– Every Object provides the getClass() method
– Various methods of Class return instances of Field, Method, Constructor,
Package, etc
● methods in plural return arrays, e.g. getFields(), getMethods()
● methods in singular return single instances according to search
criteria, e.g. getField(...), getMethod(...)
– Class can also represent primitive types, interfaces, arrays, enums and
annotations
● Java supports Class literals, e.g. String.class, int.class
● Class.forName() is used for loading classes dynamically
● Modifiers: Modifier.isPublic(clazz.getModifiers())
● getSuperclass() returns the super class
Java course – IAG0040 Lecture 9
Anton Keks Slide 12
13. Instantiating Classes
● clazz.newInstance() works for default constructors
● Otherwise getConstructor(...) will provide a Constructor
instance, which has its own newInstance(...)
● Singular Constructor and Method finding methods take Class
instances for matching of parameters:
– Constructor c = clazz.getConstructor(int.class,
Date.class);
● Then, creation (newInstance) or invocation (invoke) takes
the real parameter values:
– Object o = c.newInstance(3, new Date());
– Primitive values are autoboxed to their wrapper classes
Java course – IAG0040 Lecture 9
Anton Keks Slide 13
14. Reflection Tips
● Array class provides additional options for dynamic manipulation of arrays
● Even this works: byte[].class
● Retrieve class name of any object: object.getClass().getName()
● Don't hardcode class names in Strings:
MegaClass.class.getName() or .getSimpleName() is better
● Accessing private fields:
– boolean wasAccessible = field.getAccessible();
field.setAccessible(true);
Object value = field.get(instance);
field.setAccessible(wasAccessible);
● Dynamic proxies allow to wrap objects and intercept method calls on them
defined in their implemented interfaces:
– Object wrapped = Proxy.newProxyInstance(
o.getClass().getClassLoader(), o.getClass().getInterfaces(),
new InvocationHandler() { ... });
Java course – IAG0040 Lecture 9
Anton Keks Slide 14