0% found this document useful (0 votes)
6 views

Chapter 3 Networking in Java

The document provides an overview of networking in Java, focusing on the use of sockets for communication between computers over TCP and UDP protocols. It explains the roles of client-server architecture, the importance of ports for directing data to applications, and the functionality of the InetAddress class for handling IP addresses and hostnames. Additionally, it details the ServerSocket class for creating server applications that listen for client connections, including methods and examples for implementation.

Uploaded by

tsionyosef46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 3 Networking in Java

The document provides an overview of networking in Java, focusing on the use of sockets for communication between computers over TCP and UDP protocols. It explains the roles of client-server architecture, the importance of ports for directing data to applications, and the functionality of the InetAddress class for handling IP addresses and hostnames. Additionally, it details the ServerSocket class for creating server applications that listen for client connections, including methods and examples for implementation.

Uploaded by

tsionyosef46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

NETWORKING IN JAVA

1. Sockets
 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…
 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…
 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…
 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…
 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
 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 instead of overloading a constructor with various parameter lists
when having unique method names makes the results much clearer.
 The static factory methods connect to a DNS server to resolve a hostname.
InetAddress…
 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…
 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
byte[ ] getAddress()
address 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…
 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…
 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());
2. Sockets
 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…
 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…
 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 date 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…
 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…
 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…
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
 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
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…
 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 if the
boolean isBound()
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…
 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.
 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…
 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…
 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…
Example: closing ServerSocket
ServerSocket server = null;
try {
server = new ServerSocket(port);
//work with the server socket
} finally {
if (server != null) {
try {
server.close();
} catch (IOException ex) {
//ignore
}
}
}
2.2 Client Connection
 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…
 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…
 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
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);
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) {
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…
 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());
2.2 Client Connection…
 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…
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…
 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);
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
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…
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…
 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();
}
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;
}
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
 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…
 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…
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 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…
 Other methods of DatagramSocket:
Method Description
If a DatagramSocket is connected, the getInetAddress() method
InetAddress getInetAddress() returns the address of the remote host to which it is connected.
Otherwise, it returns null.
int getLocalPort() Returns the number of the local port.
If a DatagramSocket is connected, the getPort() method returns the
int getPort()
remote port to which it is connected. Otherwise, it returns –1.
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 to
void setSoTimeout(int millis)
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

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.
 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…
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…
 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).
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 {
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.length, “”);
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);
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.length);
System.out.println("Server: " + msg);
}
} catch (IOException e) { System.err.println("IOException " + e); }

You might also like