Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Chapter 2 Networking in Java

This document discusses networking concepts in Java including sockets, ports, InetAddress, and URL. Sockets allow Java programs to communicate over TCP and UDP network protocols. TCP provides reliable connections while UDP sends datagrams without guarantees. Ports identify applications on a computer for incoming network data. InetAddress represents IP addresses and hostnames. The URL class represents uniform resource locators and can access information across the internet.

Uploaded by

ebisa chibsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Chapter 2 Networking in Java

This document discusses networking concepts in Java including sockets, ports, InetAddress, and URL. Sockets allow Java programs to communicate over TCP and UDP network protocols. TCP provides reliable connections while UDP sends datagrams without guarantees. Ports identify applications on a computer for incoming network data. InetAddress represents IP addresses and hostnames. The URL class represents uniform resource locators and can access information across the internet.

Uploaded by

ebisa chibsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

1

CHAPTER TWO
NETWORKING IN JAVA

Socket Programming

Advanced Programming ITec30581


1. Sockets
2

 Computers running on the Internet communicate with each other using either
the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
 When you write Java programs that communicate over the network, you are
programming at the application layer.
 Typically, you don't need to concern yourself with the TCP and UDP layers.
 Instead, you can use the classes in the java.net package.
 These classes provide system-independent network communication.
 However, to decide which Java classes your programs should use, you do
need to understand how TCP and UDP differ.
1. Sockets…
3

 TCP is a connection-based protocol that provides a reliable flow of data


between two computers.
 When two applications want to communicate to each other reliably, they
establish a connection and send data back and forth over that connection.
 TCP guarantees that data sent from one end of the connection actually gets
to the other end and in the same order it was sent.
 Otherwise, an error is reported.
 HTTP, FTP, and Telnet are all examples of applications that require a
reliable communication channel.
 UDP is a protocol that sends independent packets of data, called
datagrams, with no guarantees about arrival.
 UDP is not connection-based unlike TCP.
 For many applications, the guarantee of reliability is critical to the success of
the transfer of information from one end of the connection to the other.
1. Sockets…
4

 However, other forms of communication don't require such strict standards.


 In fact, they may be slowed down by the extra overhead or the reliable
connection may invalidate the service altogether.

Ports
 Generally speaking, a computer has a single physical connection to the
network.
 All data destined for a particular computer arrives through that connection.
 However, the data may be intended for different applications/servers
running on the computer.
 So how does the computer know to which application to forward the data?
 Through the use of ports.
 Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it is destined.
1. Sockets…
5

 The computer is identified by its 32-bit IP address, which IP uses to deliver


data to the right computer on the network.
 Ports are identified by a 16-bit number, which TCP and UDP use to deliver
the data to the right application.

 In connection-based communication such as TCP, a server application binds a


socket to a specific port number.
 This has the effect of registering the server with the system to receive all
data destined for that port.
 A client can then rendezvous with the server at the server's port
1. Sockets…
6

 Port numbers range from 0 to 65,535 because ports are represented by


16-bit numbers.
 The port numbers ranging from 0 - 1023 are restricted.
 They are reserved for use by well-known services such as HTTP and FTP and
other system services.
 These ports are called well-known ports.
 Your applications should not attempt to bind to them.
InetAddress
7

 The InetAddress class is used to encapsulate both the numerical IP address


and the domain name of a computer.
 You interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address.
 The InetAddress class hides the number inside.
 InetAddress can handle both IPv4 and IPv6 addresses.
 The InetAddress class has no visible constructors and so to create an
InetAddress object, you have to use one of the available factory methods.
 Factory methods are merely a convention whereby static methods in a class
return an instance of that class.
 This is done in lieu of overloading a constructor with various parameter lists
when having unique method names makes the results much clearer.
 The static factory methods that connect to a DNS server to resolve a
hostname.
InetAddress…
8

 Three commonly used InetAddress factory methods are shown here:


 static InetAddress getLocalHost() - simply returns the InetAddress object that
represents the localhost.
 static InetAddress getByName(String hostName) throws UnknownHostException – this
returns an InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
 static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException -
On the Internet, it is common for a single name to be used to represent several
machines. The getAllByName() factory method returns an array of InetAddresses that
represent all of the addresses that a particular name resolves to.
 Throws an UnknownHostException if it can’t resolve the name to at least one address.
 static InetAddress getByAddress(byte[] addr) – this 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 index 0. IPv4 address byte array must be 4 bytes long and
IPv6 byte array must be 16 bytes long.
 static InetAddress getByAddress(String host, byte[] addr) - creates an InetAddress
based on the provided host name and IP address. No name service is checked for
the validity of the address.
InetAddress…
9

 The InetAddress class has several other methods, which can be used
on the objects returned by the methods discussed above.
 Here are some of the more commonly used methods:
Method Description
Returns a byte array that represents the object’s IP address
byte[ ] getAddress()
in network byte order.
Returns a string that represents the IP address associated
String getHostAddress()
with the InetAddress object.
Returns a string that represents the host name associated
String getHostName()
with the InetAddress object.
InetAddress…
10

 Example: creating InetAddress


class InetAddressTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.HerbSchildt.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]);
}
}
InetAddress…
11

 The bytes returned by getAddress() are unsigned, which poses a problem.


 Unlike C/C++, Java doesn’t have an unsigned byte primitive data type.
 Bytes with values higher than 127 are treated as negative numbers.
 Therefore, you need to promote the bytes to ints and make appropriate
adjustments.
 Here’s one way to do it:
int unsignedByte = signedByte < 0 ? signedByte + 256 : signedByte;
 Occasionally, you would like to know who is connecting to a server socket.
 You can use the InetAddress class to find the client’s host name and IP address.
 You can use the statement shown below in the server program to get an instance
of InetAddress on a socket that connects to the client.
InetAddress clientAddress = socket.getInetAddress();
 Next, you can display the client’s host name and IP address, as follows:
System.out.println("Client's host name is " + clientAddress.getHostName());
System.out.println("Client's IP Address is " + clientAddress.getHostAddress());
URL
12

 The URL provides a reasonably intelligible form to uniquely identify or address


information on the Internet.
 URLs are ubiquitous; every browser uses them to identify information on the Web.
 In Java, the URL class provides a simple, concise API to access information across the
Internet using URLs.
 All URLs share the same basic format, although some variation is allowed.
http://www.example.com/
http://www.example.com:80/index.htm.
 A URL specification is based on four components.
 The first is the protocol to use, separated from the rest of the locator by a colon (:).
 Common protocols are HTTP, FTP, gopher, and file.
 The second component is the host name or IP address of the host to use; this is delimited
on the left by double slashes (//) and on the right by a slash (/) or optionally a colon (:).
 The third component is the port number, delimited on the left from the host name by a
colon (:) and on the right by a slash (/).
 It defaults to port 80, the predefined HTTP port.
 The fourth part is the actual file path.
URL…
13

 Java’s URL class has several constructors and each can throw a
MalformedURLException.
 One commonly used form specifies the URL with a string that is identical to
what you see displayed in a browser:
 URL(String url) – creates a URL object from the String representation. It
throws MalformedURLException if no protocol is specified, or unknown
protocol is used, or url is null.
 URL(String protocol, String host, String file) – creates a URL from the
specified protocol name, host name, and file name. The default port for
the specified protocol is used. It throws MalformedURLException.
 URL(String protocol, String host, int port, String file ) – creates a URL
object from the specified protocol, host, port number, and file. host can
be expressed as a host name or a literal IP address. Throws
MalformedURLException.
 URL(URL urlObj, String url) - Creates a URL by parsing the given spec
within a specified context. It throws MalformedURLException.
URL…
14

 Example: creating URL in different way


URL myURL = new URL("http://example.com/pages/");
URL url = new URL("http://example.com:80/pages/abc.html");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");
URL gamelan = new URL("http", "example.com", 80, “/pages/page1.html");
 URL defines some methods that you can use to manipulate URL.
Methods description
String getProtocol() returns the protocol of this URL
String getHost() returns the host name of this URL
int getPort() returns the port number, or -1 if the port is not set
String getPath() returns the path part of this URL, or an empty string if it does not exist

String getFile() returns the file name of this URL, or an empty string if it does not exist
URLConnection opens a connection to the given URL and return URLConnection object if
openConnection() successful
URL…
15

 Example: creating URL object


class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("http://www.example.com/new/test.html");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
}
}

Protocol: http
Port: -1
Host: www.example.com
File: new/test.html
Path: new/test.html
URL…
16

 Given a URL object, you can retrieve the data associated with it.
 To access the actual bits or content information of a URL, create a
URLConnection object from it, using URL classes openConnection()
method.
 The openConnection() method has the following general form:
URLConnection openConnection() throws IOException
 It returns a URLConnection object associated with the invoking URL
object.
URLConnection
17

 URLConnection is an abstract class that represents an active connection to a


resource specified by a URL.
 It is a general-purpose class for accessing the attributes of a remote
resource.
 Once you make a connection to a remote server, you can use URLConnection
to inspect the properties of the remote resource before actually transporting
it locally.
 These attributes are exposed by the HTTP protocol specification and, as
such, only make sense for URL objects that are using the HTTP protocol.
 A URLConnection can inspect the header sent by the server and respond
accordingly.
 It can set the header fields used in the client request.
 Finally, a URLConnection can send data back to a web server with POST,
PUT, and other HTTP request methods.
Method Description
Returns the size in bytes of the content associated with the resource.
int getContentLength()
If the length is unavailable, –1 is returned.
Returns the size in bytes of the content associated with the resource.
long getContentLengthLong()
18 If the length is unavailable, –1 is returned.
Returns the type of content found in the resource. This is the value of
String getContentType() the content-type header field. Returns null if the content type is not
available.
Returns the time and date of the response represented in terms of
long getDate()
milliseconds since January 1, 1970 GMT.
Returns the expiration time and date of the resource represented in
long getExpiration() terms of milliseconds since January 1, 1970 GMT. 0 is returned if the
expiration date is unavailable.
Returns the value of the header field at index idx. Header field
String getHeaderField(int idx) indexes begin at 0. Returns null if the value of idx exceeds the
number of fields.
String getHeaderField( Returns the value of header field whose name is specified by
String fieldName) fieldName. Returns null if the specified name is not found.
String getHeaderFieldKey( Returns the header field key at index idx. Header field indexes begin
int idx) at 0. Returns null if the value of idx exceeds the number of fields.
Returns the time and date, represented in terms of milliseconds since
long getLastModified()
January 1, 1970 GMT, of the last modification of the resource.
Returns an InputStream that is linked to the resource. This stream can
InputStream getInputStream()
be used to obtain the content of the resource.
Example: using URLConnection to get information about web pages and the content too
URL hp = new URL("http://www.internic.net/index.html");
URLConnection hpCon = hp.openConnection();
long d = hpCon.getDate(); // get date
if (d != 0)
19
System.out.println("Date: " + new Date(d));
System.out.println("Content-Type: " + hpCon.getContentType());
d = hpCon.getExpiration(); // get expiration date
if (d != 0)
System.out.println("Expires: " + new Date(d));
d = hpCon.getLastModified(); // get last-modified date
if (d != 0)
System.out.println("Last-Modified: " + new Date(d));
long len = hpCon.getContentLengthLong();// get content length
if (len != -1)
System.out.println("Content-Length: " + len);
if (len != 0) {
int c;
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
while (((c = input.read()) != -1))
System.out.print((char) c);
input.close();
} else
System.out.println("No content available.");
 The getInputStream() method returns a generic InputStream that lets you read
and parse the data that the server sends.
 The following example uses the getInputStream() method to download a web
20
page.
try {
URL u = new URL("https://en.wikipedia.org/wiki/Client_server_model");
URLConnection uc = u.openConnection();
InputStream raw = uc.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(raw);
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(buffer);
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (MalformedURLException ex) {
System.err.println("It is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex);
}
HttpURLConnection
21

 Java provides a HTTP client to access resources via the HTTP or HTTPS protocol.
 The main class to access the Internet via HTTP/HTTPS is the HttpURLConnection class.
 The URL class can be used to define a pointer to a web resource while the
HttpURLConnection class can be used to access a web resource.
 HttpURLConnection is a subclass of URLConnection and it provides support for HTTP
connections.
 It provides some additional methods that are helpful when working specifically with
http URLs.
 You obtain an HttpURLConnection in the same way using URLConnection, by calling
openConnection() on a URL object, but you must cast the result to HttpURLConnection.
 Of course, you must make sure that you are actually opening an HTTP connection.
 Once you have obtained a reference to an HttpURLConnection object, you can use
any of the methods inherited from URLConnection.
HttpURLConnection…
22

 Methods of HttpURLConnection
Methods description
Returns true if redirects are automatically followed and false
static boolean getFollowRedirects()
otherwise. This feature is on by default.
Returns a string representing how URL requests are made. The default
String getRequestMethod()
is GET. Other options, such as POST, are available.
Returns the HTTP response code. –1 is returned if no response code
int getResponseCode()
can be obtained. An IOException is thrown if the connection fails.
Returns the response message associated with the response code.
String getResponseMessage() Returns null if no message is available. An IOException is thrown if the
connection fails.
If how is true, then redirects are automatically followed. If how is false,
static void
redirects are not automatically followed. By default, redirects are
setFollowRedirects(boolean how)
automatically followed.
Sets the method by which HTTP requests are made to that specified by
setRequestMethod(String how) how. The default method is GET, but other options, such as POST, are
available. If how is invalid, a ProtocolException is thrown.
Returns an InputStream that is linked to the resource. This stream can
InputStream getInputStream()
be used to obtain the content of the resource.
 HttpURLConnection allows you to create an InputStream.
 Once you have access to an InputStream you can read it similarly to an InputStream
from a local file.

 Example: download a web page and display it


23
public class DownloadWebpage {
public static void main(String[] args) {
try {
URL url = new URL("http://www.vogella.com/test.html");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String rs = readStream(con.getInputStream());
System.out.println(rs);
} catch (Exception e) { e.printStackTrace(); }
}
private static String readStream(InputStream in) {
String sb = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null)
sb += nextLine + "\n";
} catch (IOException e) { e.printStackTrace(); }
return sb.toString();
}
}
2. Sockets
24

 Most modern network programming is based on a client-server model.


 A client-server application typically stores large quantities of data on an expensive,
high-powered server while most of the program logic and the user interface is
handled by client software running on relatively cheap personal computers.
 In most cases, a server primarily sends data while a client primarily receives it; but it
is rare for one program to send or receive exclusively.
 A more reliable distinction is that a client initiates a conversation while a server waits
for clients to start conversations with it.
 By far, the most popular client-server system on the Internet is the Web(WWW).
 Web servers like Apache respond to requests from web clients like Firefox.
 Data is stored on the web server and is sent out to the clients that request it.
 Aside from the initial request for a page, almost all data is transferred from the
server to the client, not from the client to the server.
 FTP is an older service that fits the client-server model.
 People often use FTP to upload files from the client to the server, so it’s harder to say
that the data transfer is primarily in one direction, but it is still true that an FTP client
initiates the connection and the FTP server responds.
2. Sockets…
25

 In client-server applications, the server provides some service, such as processing


database queries or sending out current stock prices.
 The client uses the service provided by the server, either displaying database
query results to the user or making stock purchase recommendations to an
investor.
 The communication that occurs between the client and the server must be
reliable.
 That is, no data can be dropped and it must arrive on the client side in the same
order in which the server sent it.
 A socket is one end-point of a two-way communication link between two
programs running on the network.
 Socket classes are used to represent the connection between a client program
and a server program.
 Java provides two classes, Socket and ServerSocket, that implement the client
side of the connection and the server side of the connection, respectively.
 A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent.
2. Sockets…
26

 Normally, a server runs on a specific computer and has a socket that is


bound to a specific port number.
 The server just waits, listening to the socket for a client to make a connection
request.
 On the client-side, the client knows the hostname of the machine on which the
server is running and the port number on which the server is listening.
 To make a connection request, the client tries to rendezvous with the server
on the server's machine and port.
 The client also needs to identify itself to the server so it binds to a local port
number that it will use during this connection.
 This is usually assigned by the system.
2. Sockets…
27

 If everything goes well, the server accepts the connection.


 Upon acceptance, the server gets a new socket bound to the same local port
and also has its remote endpoint set to the address and port of the client.
 It needs a new socket so that it can continue to listen to the original socket
for connection requests while tending to the needs of the connected client.

 On the client side, if the connection is accepted, a socket is successfully


created and the client can use the socket to communicate with the server.
 The client and server can now communicate by writing to or reading from
their sockets.
2. Sockets…
28

 The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program
and another program on the network.
 The Socket class sits on top of a platform-dependent implementation, hiding
the details of any particular system from your Java program.
 By using the java.net.Socket class instead of relying on native code, your
Java programs can communicate over the network in a platform-
independent fashion.
2. Sockets…
29

Types of Sockets
 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.
 The Socket class is designed to connect to server sockets and initiate
protocol exchanges.
 The creation of a Socket object implicitly establishes a connection between
the client and server.
 Once the Socket object has been created, it can also be examined to gain
access to the input and output streams associated with it.
 The methods of socket can throw an IOException if the sockets have been
invalidated by a loss of connection on the network.
2.1 TCP Server Sockets
30

 Java provides a ServerSocket class that represents server sockets.


 The ServerSocket class is used to create a server that listens for client
programs to connect to it on published ports.
 A server socket runs on the server and listens for incoming TCP connections.
 Each server socket listens on a particular port on the server machine.
 When a client on a remote host attempts to connect to that port, the server
negotiates the connection between the client and the server, and returns a
regular Socket object representing the socket between the two hosts.
 In other words, server sockets wait for connections from clients.
 Once a ServerSocket has set up the connection, the server uses a regular
Socket object to send data to the client.
 Data always travels over the regular socket.
 When you create a ServerSocket, it will register itself with the system as
having an interest in receiving client connections.
 The constructors for ServerSocket reflect the port number that you wish to
31 accept connections on and, optionally, how long you want the queue for said
port to be.
 The queue length tells the system how many client connections it can leave
pending before it should simply refuse connections.
 The default is 50.
 The constructors might throw an IOException under adverse conditions.
 Here are the constructors:
 ServerSocket(int port) - creates server socket on the specified port with a
queue length of 50 by default.
 ServerSocket(int port, int maxQueue) - creates a server socket on the
specified port with a maximum queue length of maxQueue.
 ServerSocket(int port, int maxQueue, InetAddress localAddress) - creates
a server socket on the specified port with a maximum queue length of
maxQueue. On a multihomed host, localAddress specifies the IP address
to which this socket binds.
2.1 TCP Server Sockets…
32

 Methods of ServerSocket
Methods description
InetAddress getInetAddress() It returns the local address occupied by the server socket.
int getLocalPort() It returns the local port occupied by the server socket.
It returns the binding state of the ServerSocket. It returns true returns
boolean isBound()
true if the ServerSocket has ever been bound to a port.
It listens for a connection to be made to this socket and accepts it. The
Socket accept() method blocks until a connection is made. It throws IOException if an
I/O error occurs when waiting for a connection.
Returns the closed state of the ServerSocket. It returns true if the
boolean isClosed()
socket has been closed.
Closes this server socket. Any thread currently blocked in
void close() ServerSocket.accept() will throw a SocketException. It throws
IOException if an I/O error occurs when closing the socket.
Sets the default receive buffer size for sockets accepted by the server
setReceiveBufferSize(int size) socket. This controls the suggested send buffer size used for
network input.
Returns the value of the buffer size that will be used for Sockets
int getReceiveBufferSize()
accepted from this ServerSocket.
2.1 TCP Server Sockets…
33

 Example: creating a server that listens for clients on port 4444


ServerSocket servSocket;
try {
servSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
 ServerSocket provides a system-independent implementation of the server
side of a client-server socket connection.
 The constructor for ServerSocket throws an exception if it can't listen on the
specified port (for example, the port is already being used).
 If the server successfully binds to its port, then the ServerSocket object is
successfully created and the server continues to accept a connection from a
client.
 ServerSocket has a method called accept(), which is a blocking call that will
wait for a client to initiate connections
 It then return a normal Socket that is then used for communication with the
client.
34  The accept() method returns a Socket object connecting the client and the
server.
 Example: accepting client request on the server after creating the listener
ServerSocket servSocket ;
Socket socket = null;
try {
servSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
try {
socket = servSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
2.1 TCP Server Sockets…
35

 Server manages each client connection with a Socket object.


 After binding the server to a port with a ServerSocket, the server listens
indefinitely (or blocks) for an attempt by a client to connect.
 To listen for a client, the program calls accept() method of ServerSocket as
in
Socket connection = server.accept();
 This statement returns a Socket object when a connection with a client is
established.
2.1 TCP Server Sockets…
36

 If you’re finished with a server socket, you should close it, especially if the
program is going to continue to run for some time.
 This frees up the port and other programs may use it if necessary.
 Closing a ServerSocket should not be confused with closing a Socket.
 Closing a ServerSocket frees a port on the local host and it also breaks all
currently open sockets that the ServerSocket has accepted.
 Server sockets are closed automatically when a program dies, so it’s not
absolutely necessary to close them.
 Nonetheless, it is a good practice to close the socket before the program
ends.
 Programmers often follow the approach “close if-not-null” in finally block.
2.1 TCP Server Sockets…
37

Example: closing ServerSocket


ServerSocket server = null;
try {
server = new ServerSocket(port);
//work with the server socket
} finally {
if (servScoket != null) {
try {
servSocket.close();
} catch (IOException ex) {
//ignore
}
}
}
2.2 Client Connection
38

 A socket is a connection between two hosts.


 The Socket class is Java’s fundamental class for performing client-side TCP
operations.
 Other client-oriented classes that make TCP network connections such as URL,
URLConnection, HttpURLConnection, Applet, and JEditorPane all ultimately
end up invoking the methods of this class.
 The Socket class itself uses native code to communicate with the local TCP
stack of the host operating system.
 Socket can perform four basic operations: connect to a remote machine,
send data, receive data, and close a connection.
 Java programs normally use client sockets in the following fashion:
 the program creates a new socket using a constructor
 the socket attempts to connect to the remote host
 Once connection established, the local and remote hosts get input and
output streams from the socket and use those streams to send data to
each other.
 The connection established by Socket is full-duplex where both hosts can
send and receive data simultaneously.
2.2 Client Connection…
39

 The Socket class constructor specifies the host and the port to connect to.
 Hosts may be specified as an InetAddress or a String.
 Remote ports are specified as int values from 1 to 65535:
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress host, int port) throws IOException
 These constructors connect the server socket i.e. an active network connection
is established to the remote host.
 If the connection can’t be opened for some reason, the constructor throws an
IOException or an UnknownHostException.
 Example: client connection to a server
try {
Socket ss = new Socket("10.140.150.20", 80);
// send and receive data...
} catch (UnknownHostException ex) {
System.err.println(ex);
} catch (IOException ex) { System.err.println(ex); }
2.2 Client Connection…
40

 Once Socket is created, it is possible to start sending and receiving data


after that.
 If the socket cannot be opened for some reason, the constructor throws an
IOException.
 There are many reasons a connection attempt might fail: the host you’re
trying to reach may not accept connections on that port, or routing problems
may be preventing your packets from reaching their destination.
 Because this constructor doesn’t just create a Socket object but also tries to
connect the socket to the remote host, you can use the object to determine
whether connections to a particular port are allowed.
 Using this, you can write a port scanner that checks which ports are occupied
and which ports are available.
Method Description
It returns an input stream for reading bytes from this socket. IOException - if an I/O
InputStream getInputStream() error occurs when creating the input stream, the socket is closed, the socket is not
connected, or the socket input has been shutdown.
It returns an output stream for writing bytes to this socket. It throws IOException if
41
OutputStream getOutputStream() an I/O error occurs when creating the output stream or if the socket is not
connected.
Returns the connection state of the socket. Returns true if the socket was
boolean isConnected()
successfully connected to a server
Closes this socket. Any thread currently blocked in an I/O operation upon this socket
void close()
will throw a SocketException.
boolean isClosed() Returns the closed state of the socket. Returns true if the socket has been closed.
Returns whether the read-half of the socket connection is closed. Returns true if the
boolean isInputShutdown()
input of the socket has been shutdown.
Returns whether the write-half of the socket connection is closed. Returns true if
boolean isOutputShutdown()
the output of the socket has been shutdown.
int getPort() Returns the remote port number to which this socket is connected.
int getLocalPort() Returns the local port number to which this socket is bound.
It returns the remote IP address to which this socket is connected, or null if the
InetAddress getInetAddress()
socket is not connected.
InetAddress getLocalAddress() Gets the local address to which the socket is bound.
The method suggests a number of bytes to use for buffering output on this socket.
setSendBufferSize(int size)
The OS is free to ignore this suggestion.
int getSendBufferSize() Returns the value of the buffer size used by the platform for output on this Socket.
The method suggests a number of bytes to use for buffering input from this socket.
setReceiveBufferSize(int size)
However, the underlying implementation is free to ignore this suggestion.
int getreceiveBufferSize() It returns the actual size of the receive buffer.
private ServerSocket serverSocket;
Example: server side that waits for clients to
public ServerListening() {
connect to it
try {
serverSocket = new ServerSocket(110);
42
startServer();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public void startServer() {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
while (true) {
try {
Socket socket = serverSocket.accept();
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(socket.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Thank you for connecting to " + socket.getLocalSocketAddress());
out.writeUTF("\nGoodbye!");
socket.close();
}catch (IOException e) {
e.printStackTrace(); break;
}
Example: a client program that connects to a server by using a socket and sends a
greeting, and then waits for a response.
public class ClientConnection {
public static void main(String[] args) {
43 String serverName = "10.120.130.140";
int port = 110;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from client");

InputStream inFromServer = client.getInputStream();


DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.2 Client Connection…
44

 When you create a server socket, you have to specify a port (e.g. 800) for
the socket.
 When a client connects to the server, a socket is created on the client.
 This socket has its own local port.
 This port number (e.g. 2047) is automatically chosen by the JVM.

 To see the local port on the client, you can write the following code on the
client side
System.out.println("local port: " + socket.getLocalPort());
 Using Socket, it is possible to check the ports that are occupied and that are available
on your computer.
 This can be done using simple port scanner that iterates over all ports and try to

connect to thereby determining if it is occupied or not.


45 public class LowPortScanner {

public static void main(String[] args) {


String host = "127.0.0.1";
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
s.close();
} catch (UnknownHostException ex) {
System.err.println(ex);
break;
} catch (IOException ex) {
System.out.println("Port " + i + " is available.");
}
}
}
}
2.2 Client Connection…
46

 The close() method shuts down both input and output from the socket by
closing the socket.
 On occasion, you may want to shut down only half of the connection, either
input or output.
 The shutdownInput() and shutdownOutput() methods close only half the
connection:
void shutdownInput()
void shutdownOutput()
 Neither actually closes the socket.
 Instead, they adjust the stream connected to the socket so that it thinks it’s at
the end of the stream.
 Further reads from the input stream after shutting down input return –1.
 Further writes to the socket after shutting down output throw an IOException.
2.2 Client Connection…
47

Reading from and Writing to Sockets


 After the server accepts the connection and Socket is created, communication
between server and client is conducted using I/O streams.
 The InputStream and OutputStream streams are used to read or write bytes
to sockets.
 To get an input stream, use the getInputStream() method on a socket object.

 To get an output stream, use the getOutputStream() method on a socket


object.
 For example, the following statements create an InputStream stream and an
OutputStream stream from a socket:
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
 The InputStream and OutputStream streams are used to read or write bytes.

 You can use DataInputStream, DataOutputStream, BufferedReader, and


PrintWriter to wrap on the InputStream and OutputStream to read or write
data, such as int, double, or String.
2.2 Client Connection…
48

 The following statements, for instance, create a DataInputStream stream


and a DataOutputStream stream to read and write primitive data
values:
DataInputStream input = new DataInputStream (socket.getInputStream());
DataOutputStream output = new DataOutputStream (socket.getOutputStream());
 The server can use input.readDouble() to receive a double value from
the client, and output.writeDouble(d) to send double value d to the
client.
public class CircleServer extends JFrame {
private JTextArea jta = new JTextArea();
public CircleServer() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
49
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
while (true) {
Socket socket = serverSocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
//receive radius from the client
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
//send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area computed: " + area + '\n');
}
} catch (IOException ex) { System.err.println(ex); }
}}
public class CircleClient extends JFrame { class TextFieldListener implements ActionListener {
private JTextField jtf = new JTextField(); public void actionPerformed(ActionEvent e) {
private JTextArea jta = new JTextArea(); try {
private DataOutputStream toServer; double radius = Double.parseDouble(jtf.getText());
private DataInputStream fromServer;
//send radius to server
50
public CircleClient() {
toServer.writeDouble(radius);
JPanel p = new JPanel();
toServer.flush();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
// Get area from the server
p.add(jtf, BorderLayout.CENTER);
double area = fromServer.readDouble();
jtf.setHorizontalAlignment(JTextField.RIGHT);
jta.append("Radius is " + radius + "\n");
setLayout(new BorderLayout());
jta.append("Area received : " + area + '\n');
add(p, BorderLayout.NORTH);
} catch (IOException ex) {
add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(new TextFieldListener()); System.err.println(ex);
setTitle("Client"); }
setSize(500, 300); }
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
setVisible(true); // It is necessary to show the frame here!
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) { jta.append(ex.toString() + '\n'); }
}
2.2 Client Connection…
51

Serving Multiple Clients


 Multiple clients are quite often connected to a single server at the same time.

 Typically, a server runs continuously on a server computer, and clients from all
over the Internet/LAN can connect to it.
 You can use threads to handle the server’s multiple clients simultaneously.

 Simply create a thread for each connection.

ServerSocket serverSocket = new ServerSocket(110);


while (true) {
Socket socket = serverSocket.accept(); //connect to a client
Thread thread = new ThreadClass(socket);
thread.start();
}
 This server socket can have many connections.
 Whenever a connection is established, a new thread is created to handle
communication between the server and the new client; and this allows multiple
connections to run at the same time.
2.2 Client Connection…
52

 The CircleServer example given above can only serve a single


client at a time.
 It cannot accept multiple connections from different clients at
the same time.
 This is a big limitation for the server which is expected to serve
multiple clients.
 This problem can be solved by using thread.
 The following example shows how to do that.
public class ThreadedCircleServer extends JFrame {
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new ThreadedCircleServer();
53 }
public ThreadedCircleServer() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
//loop and accept multiple connections
while (true) {
Socket socket = serverSocket.accept();
Communicate comm = new Communicate(socket);
comm.start();
}
} catch (IOException ex) { ex.printStackTrace(); }
}
class Communicate extends Thread {
Socket socket;
Communicate(Socket ss) {
socket = ss;
54 }
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while (true) {
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;

outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area computed: " + area + '\n');
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
2.2 UDP Datagrams
55

 Some applications that you write to communicate over the network will not
require the reliable, point-to-point channel provided by TCP.
 Rather, your applications might benefit from a mode of communication that
delivers independent packages of information whose arrival and order of
arrival are not guaranteed.
 The UDP protocol provides a mode of network communication whereby
applications send packets of data, called datagrams, to one another.
 Datagrams are bundles of information passed between machines.
 A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
 Once the datagram has been released to its intended target, there is no
assurance that it will arrive at the destination.
 Likewise, when the datagram is received, there is no assurance that it hasn’t
been damaged in transit or that whoever sent it is still there to receive a
response.
2.2 UDP Datagrams…
56

 UDP is appropriate for data transfers where it doesn't matter if a packet is


lost in transition.
 For instance, imagine a transfer of a live TV-signal over the internet.
 You want the signal to arrive at the clients as close to live as possible.
 Therefore, if a frame or two are lost, you don't really care.
 You don't want the live broadcast to be delayed just to make sure all frames
are shown at the client.
 You'd rather skip the missed frames, and move directly to the newest frames
at all times.
 Java implements datagrams on top of the UDP protocol by using two
classes:
 the DatagramPacket which is the data container

 the DatagramSocket which is the mechanism used to send or receive the


DatagramPacket.
2.2 UDP Datagrams…
57

A. DatagramSocket
 A DatagramSocket sends as well as receives UDP datagrams.
 To send data, you put the data in a DatagramPacket and send the packet
using a DatagramSocket.
 To receive data, you take a DatagramPacket object from a DatagramSocket
and then inspect the contents of the packet.
 The DatagramSocket themselves are very simple creatures.
 In UDP, everything about a datagram, including the address to which it is
directed, is included in the packet itself.
 The socket only needs to know the local port on which to listen or send.
 DatagramSocket defines four public constructors.
 DatagramSocket() – this creates a DatagramSocket bound to any unused
port on the local computer.
 DatagramSocket(int port) – creates a DatagramSocket bound to the port
58 specified by port.
 DatagramSocket(int port, InetAddress ip) – constructs a DatagramSocket
bound to the specified port and InetAddress.
 DatagramSocket(SocketAddress address) – this creates a
DatagramSocket bound to the specified SocketAddress.
InetSocketAddress encapsulates an IP address with a port number.
 All can throw a SocketException if an error occurs while creating the socket.
 DatagramSocket defines many methods.
 Two of the most important are send() and receive():
 send(DatagramPacket packet) – this method sends a packet to the
address specified by packet. The DatagramPacket includes information
indicating the data to be sent, its length, the IP address of the remote
host, and the port number on the remote host. It throws IOException if
there is an input-output error.
 receive(DatagramPacket packet) – this method waits for a packet to be
received and returns the result. When this method returns, the
DatagramPacket's buffer is filled with the data received. This method
blocks until a datagram is received. It throws IOException if there is an
input output error.
2.2 UDP Datagrams…
59

 Other methods of DatagramSocket:

Method Description
if the socket is connected, then the address is returned. Otherwise,
InetAddress getInetAddress()
null is returned.
int getLocalPort() Returns the number of the local port.

Returns the number of the port to which the socket is connected. It


int getPort()
returns –1 if the socket is not connected to a port.

Returns true if the socket is bound to an address. Returns false


boolean isBound()
otherwise.
Returns true if the socket is connected to a server. Returns false
boolean isConnected()
otherwise.
Sets the time-out period to the number of milliseconds passed
waiting for data. With this option set to a non-zero timeout, a call
void setSoTimeout(int millis)
to receive() for this DatagramSocket will block for only this amount
of time. If the timeout expires, a SocketTimeoutException is raised.
UDP Client
 Both UDP server and UDP client are created using DatagramSocket.

 The only difference is the port they bind to: the server socket should bind to

60 fixed port whereas the client should not.


 Let us retrieve some data programmatically using UDP client.

 First, open a socket on port 0:

DatagramSocket socket = new DatagramSocket(0);


 You only specify a local port to connect to.

 The socket does not know the remote host or address.

 By specifying port 0 you ask Java to pick a random available port for you,

much as with server sockets.


 Next step is to set a timeout on the connection using the setSoTimeout()
method.
 This tells the socket to time out after 10 seconds of non-responsiveness:

socket.setSoTimeout(10000);
 Timeouts are even more important for UDP than TCP because many

problems that would cause an IOException in TCP silently fail in UDP.


 For example, if the remote host is not listening on the targeted port, you’ll

never hear about it.


UDP Server
 A UDP server follows almost the same pattern as a UDP client, except that
you usually receive data before sending & also use a fixed port to bind to.
61  Unlike TCP, there’s no separate DatagramServerSocket class.
 To create UDP server, begin by opening a datagram socket on a well-known
port.
DatagramSocket socket = new DatagramSocket(13);
 Next, create a packet into which to receive a request.
 You need to supply both a byte array in which to store incoming data, the
offset into the array, and the number of bytes to store.
 Here you set up a packet with space for 1,024 bytes starting at 0:
DatagramPacket request = new DatagramPacket(new byte[1024], 0, 1024);
socket.receive(request);
 This call blocks indefinitely until a UDP packet arrives on port 13.
 When it does, Java fills the byte array with data and the receive() method
returns.
2.2 UDP Datagrams…
62

B. DatagramPacket
 To send data via Java's DatagramSocket you must first create a
DatagramPacket.
 DatagramPacket objects store packets of data for sending or store packets
of data received by an application.
 DatagramSockets send and receive DatagramPackets.

 DatagramPacket defines several constructors.

 Some of these constructors are for creating a DatagramPacket for receiving


data while others are for sending data.
 For receiving data with DatagramPacket, you can use the following
constructors:
 DatagramPacket(byte data [], int size) – this specifies a buffer that will
receive data and the size of a packet. It is used for receiving data over
a DatagramSocket.
 DatagramPacket(byte data [], int offset, int size) - the second form allows
you to specify an offset into the buffer at which data will be stored.
2.2 UDP Datagrams…
63

 For sending packets, you can create DatagramPacket using the following
constructors:
 DatagramPacket(byte data [], int length, InetAddress ip, int port) - this
specifies a target address and port, which are used by a DatagramSocket
to determine where the data in the packet will be sent.
 DatagramPacket(byte data [], int offset, int length, InetAddress ip, int port) –
same as the above method except this transmits packets beginning at the
specified offset into the data.
 DatagramPacket(byte[] data, int length, SocketAddress destination) – creates
a datagram packet for sending packets of the given length to the computer
specified by SocketAddress.
 DatagramPacket(byte[] data, int offset, int length, SocketAddress destination)
– creates a datagram packet for sending packets of the given length
starting from the given offset. The data is sent to the specified port number
and the machine specified with the given SocketAddress.
 DatagramPacket Methods
Method Description
Returns the address of the source (for datagrams being received) or
InetAddress getAddress( )
destination (for datagrams being sent).
64
Returns the byte array of data contained in the datagram. Mostly used
byte[ ] getData( )
to retrieve data from the datagram after it has been received.
Returns the length of the valid data contained in the byte array that
int getLength( ) would be returned from the getData() method. This may not equal the
length of the whole byte array.
int getOffset( ) Returns the starting index of the data.
The method returns an integer specifying the remote port. If this
datagram was received from the Internet, this is the port on the host
int getPort( ) that sent the packet. If the datagram was created locally to be sent to a
remote host, this is the port to which the packet is addressed on the
remote machine.
void setPort(int port) This method sets the port a datagram is addressed to.
Sets the address to which a packet will be sent. The address is specified
setAddress(InetAddress ip)
by InetAddress.
Sets the data to data, the offset to zero, and the length to number of
void setData(byte[ ] data)
bytes in data.
setData(byte[ ] data, int idx,
Sets the data to data, the offset to idx, and the length to size.
int size)
void setLength(int size) Sets the length of the packet to size.
 Example: UDP server that sends hello message to all clients
DatagramSocket sock = null;
Scanner sc = new Scanner(System.in);
try {
65 sock = new DatagramSocket(7777);
//buffer to receive incoming data
byte[] buffer = new byte[8192];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
System.out.println("Server socket created. Waiting for incoming data...");
//communication loop
while (true) {
sock.receive(incoming);
byte[] data = incoming.getData();
String str = new String(data, 0, incoming.getLength());
System.out.println("Client: " + str);
System.out.print("Server: ");
String msg = sc.nextLine();
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.getBytes().length,
incoming.getAddress(), incoming.getPort());
sock.send(dp);
}
} catch (IOException e) {
System.err.println("IOException " + e);
}
Example: UDP client that can connect to the above UDP server
DatagramSocket sock = null;
String str;
Scanner sc = new Scanner(System.in);
66 try {
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
int port = 7777;
while (true) {
System.out.print("Client: ");
str = sc.nextLine();
byte[] b = str.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, host, port);
sock.send(dp);
//now receive reply
byte[] buffer = new byte[8192];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
String msg = new String(data, 0, reply.getLength());
System.out.println("Server: " + msg);
}
} catch (IOException e) { System.err.println("IOException " + e); }

You might also like