Networking in Java
Networking in Java
Networking in Java
Objectives:
Learn about the basic java classes (java.net package) that supports Socket programming, namely:
o Basic network concepts
o InetAddress
o Socket
o ServerSocket
o DatagramSocket
o DatagramPacket
o MulticastSocket
Learn how to use these classes to create Tcp, Udp and Multicast Client-Server applications.
Network Programming
• A network allows arbitrary applications to communicate.
• However, a network programmer doesn’t need to know the details of all lower-level network technologies.
• Network facilities are accessed through an Application Programming Interface (API); e.g., a Service Interface.
Static InetAddress getByName(String host) Takes a hostname and returns InetAddress object representing its IP
address.
Static InetAddress[] getAllByName(String Takes a hostname and returns an array of InetAddress objects representing
host) its IP addresses.
static InetAddress getLocalHost() Returns an InetAddress object representing the IP address of the local host
String getHostAddress() Returns IP address string of this InetAddress object
string getHostName() Returns the hostname of this InetAddress object.
boolean isLoopbackAddress() Checks if the InetAddress is a loopback address.
boolean isMulticastAddress() Checks if the InetAddress is an IP multicast address.
The following example first prints the Address of the current machine and then in a loop reads a host or an address
from a user and resolving it.
import java.net.*;
import java.io.*;
while (true) {
System.out.print("host name or IP to resolve - <exit> to quit: ");
String input = stdin.readLine();
if (input.equalsIgnoreCase("exit"))
break;
TCP
Transmission Control Protocol:
RFC 793
It’s a reliable connection-oriented protocol
Reliability is achieved using packets indexing and generating “ack” messages for each received packet
Creating a connection is an asymmetrical process; once the connection is established the protocol becomes
symmetric
Ports are used to initiate a connection
Ports
IP address isn’t enough to identify a unique server
Many servers can exist on one machine
IP machines also contain port numbers
When you set up client and server, you must specify IP address and port, so they can find each other
A port is a 16-bit number, 0-65535
• Some protocols work on specific ports
• Can’t create a server on a port below 1024
• Unless you are root (or equivalent)
• Usually the system assign the client’s port
21 FTP
23 Telnet
80 HTTP
110 POP3
119 NNTP
TCP Protocol
There is a server process P2 and a client process P1. P1 and P2 establish a communication line between them
using TCP sockets. P1 reads a message from the user and places that message on the socket. The message
reaches socket in P2. P2 reads the message from the socket and displays it. Also P2 sends back the same
message to P1 by placing it on the socket. P1 reads the message from the socket and displays it to the user.
The following are the system calls that are to be executed for connection oriented communication between two processe
Usually computers running on the Internet communicate to each other using either the Transmission Control Protocol
(TCP) or the User Datagram Protocol (UDP):
Java provides two classes for creating TCP sockets, namey, Socket and ServerSocket.
A socket is one endpoint of a two-way communication link between two programs running on the network.
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 to which the server is connected. To make a connection request, the client tries to rendezvous with the server
on the server's machine and port.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to a
different port. It needs a new socket (and consequently a different port number) 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.
Compiled By G/egziabher T Page 6
To do is you should perform five basic steps:
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.
Creating socket
Socket client = new Socket(“www.microsoft.com", 80);
Note that the Socket constructor attempts to connect to the remote server - no separate connect() method is provided.
The Socket class has the following methods, that retruns InputStream and the OutputStream for reading and
writing to the socket
Creating a ServerSocket
ServerSocket server = new ServerSocket(80, 50);
accept() method returns a Socket object, and its getInputStream() and getOutputStream() methods provide streams
for reading and writing to the client.
Example 2: The following examples show how to create TcpEchoServer and the corresponding TcpEchoClient.
import java.net.*;
import java.io.*;
import java.util.*;
try {
ServerSocket server = new ServerSocket(port);
while(true) {
System.out.println("Waiting for clients on port " + port);
Socket client = server.accept();
writer.println("Welcome to my server");
writer.flush();
message = reader.readLine();
}
client.close();
}
} catch(Exception ex) {
System.out.println("Connection error: "+ex);
}
}
}
try {
String host = InetAddress.getLocalHost().getHostName();
Socket client = new Socket(host, port);
String message;
while (true) {
System.out.print("Enter message to echo or Exit to end : ");
message = stdin.readLine();
writer.println(message);
writer.flush();
System.out.println("Echo from server: "+reader.readLine());
}
client.close();
try {
ServerSocket server = new ServerSocket(port);
try {
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream());
writer.println("Welcome to my server");
writer.flush();
message = reader.readLine();
message = reader.readLine();
}
client.close();
count--;
System.out.println("Active Connections = " + count);
Exercise:- develop a socket program using GUI that performs chat operation or textual communication between client and server
using TCP protocol.
UDP Protocol
There is a server process p2 and a client process p1. p1 and p2 communicate with each other using
datagram sockets based on User Datagram Protocol (UDP), in which there is no connection between the 2
processes.
P1 reads a message from the user and places that message on the socket. It reaches socket of p2. p2
reads the message and displays it. Also p2 sends back the same message to p1 by placing it on the socket. P1
reads the message from the socket and displays it to the user.
The following are the system calls that are to be executed for connectionless communication between 2
processes that uses UDP protocol.
Notes:
After receiving, use the getPort() and getAddress() on the received packet to know where the packet came
from. Also use getData() to retrieve the data, and getLength() to see how many bytes were in the data
The received packet could be truncated to fit the buffer
Example 5: The following examples show how to create a UdpEchoServer and the corresponding UdpEchoClient.
import java.net.*;
import java.io.*;
DatagramPacket packet;
DatagramSocket socket;
byte[] data;
int clientPort;
InetAddress address;
String str;
int recvSize;
}catch(IOException ex){
System.out.println("Could not Send "+ex.getMessage());
System.exit(0);
}} } }
try {
System.out.print("Enter server name: ");
address = InetAddress.getByName(stdin.readLine());
System.out.print("Enter server port: ");
port = Integer.parseInt(stdin.readLine());
while (true) {
System.out.print("Enter message for the server or press enter to exit: ");
messageSend = stdin.readLine();
if(messageSend.length() == 0){
System.exit(0);
}
The MulticastSocket class is a subclass of the DatagramSocket class, with the following methods for joining and
leaving a multicast group added.
void joinGroup(InetAddress mcastaddr)
void leaveGroup(InetAddress mcastaddr)
void setTimeToLive(int ttl)
Example 6: The following examples shows a sample Multicast sender and receiver.
import java.io.*;
import java.net.*;
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(buffer, buffer.length);
receiver.receive(recvPacket);
import java.io.*;
import java.net.*;
while (true) {
System.out.print("Enter message for Multicast: ");
String message = stdin.readLine();
if (message.length() == 0) {
sender.leaveGroup(group);
sender.close();
break;
}
DatagramPacket packet =
new DatagramPacket(message.getBytes(), message.length(), group, 9095);
sender.send(packet);
}
}
catch (Exception ex) {
System.out.println("Exception: "+ ex);
}
}
}