Banasthali University Contents Introduction to networks TCP/IP Sockets A simple client program A simple server program A server with multiple clients Example a simple email program URL connections Advanced networking technologies in Java Introduction to Networks Network programming is surprisingly easy in Java Most of the classes relevant to network programming are in the java.net package Sending data out onto a network involves attaching a stream to a network connection (socket) The main issues to consider are client/server architectures and attaching multiple clients to a server First we will look an introduction to networking and the TCP/IP protocol
Internet Protocol (IP) Data is transmitted between computers in packets Each packet is marked with a destination address
130.65.83.25 30 data Internet Client Server Server Ports 14 30 80 Network packet Each 4 byte address is the IP address Normally we refer to computers with domain names www.bham.ac.uk java.sun.com The translation from domain name to IP address is carried out using DNS (Domain Name Service) IP has no provision for re-transmission in case of failure to deliver packets This is the job of the Transmission Control Protocol (TCP) Most internet programs (eg the WWW, email etc) are based on TCP/IP
TCP/IP Sockets A TCP/IP socket enables a java program running on a client machine to open a connection with a web server There is a socket on both the client and server sides Client server communication is carried out through input and output streams Client socket Server socket Client output stream Server input stream Client input stream Server output stream A simple client program Java has a Socket object which is an abstraction for a TCP/IP network endpoint to a client computer
Connects to a server specified by the hostname java.sun.com and creates I/O streams int HTTP_PORT=80; Socket s= new Socket(java.sun.com,HTTP_PORT); InputStream instream=s.getInputStream(); OutputStream outstream=s.getOutputStream(); We can also directly specify the IP address instead of a string Java has a InetAddress class to specify IP addresses Factory Methods Static InetAddress getLocalHost() throws UnknownHostException Static InetAddress getByName(String hostname) throws UnknownHostException Static InetAddress getAllByName(String hostName) throws UnknownHostException Static InetAddress getByAddress(IP) throws UnknownHostException Instance Methods Boolean equals(Object o) Byte[] getAddress() String getHostAddress() String getHostName() String toString()
int HTTP_PORT=80; InetAddress address=InetAddress(java.sun.com); Socket s= new Socket(address,HTTP_PORT); Note that Java also provides a mechanism for the user datagram protocol (UDP) which is a simpler transport protocol that TCP The Datagram socket is the abstraction to a UDP socket The difference between TCP and UDP is like the difference between a telephone conversation (albeit sent in packets) and sending a letter
import java.io.*; import java.net.*; public class Client{ public static void main(String args[]) throws IOException { String serverResponse; Socket connectionSocket = new Socket("localhost",3500); PrintWriter printWriter = new PrintWriter(connectionSocket.getOutputStream(), true); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); System.out.println("Connected to Server."); BufferedReader ClientInputReader = new BufferedReader(new InputStreamReader(System.in)); String ClientInput; while ((ClientInput = ClientInputReader.readLine()) != null) { printWriter.println(ClientInput); if ((serverResponse = bufferedReader.readLine()) != null) { System.out.println(serverResponse); } } printWriter.close(); bufferedReader.close(); ClientInputReader.close(); connectionSocket.close(); }} A simple server program A server is a program which waits for a client to connect to it at a specified port Normally a server would specify some application level protocol (such as HTTP) enabling clients to interact with the server
A ServerSocket object is created to establish a server connection The accept() method then waits for a client to connect accept() waits indefinitely and returns a Socket object that represents the connection to the client int portNumber=8250; ServerSocket s=new ServerSocket(portNumber); Socket clientSoc=s.accept(); import java.io.*; import java.net.*; public class Server{ public static void main(String args[]) throws IOException { String userInput; ServerSocket serverSocket = new ServerSocket(3500); System.out.println("Server started. Awaiting connection requests..."); Socket connectionSocket = serverSocket.accept(); System.out.println("Server accepted connection from client."); PrintWriter printWriter = new PrintWriter(connectionSocket.getOutputStream(), true); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((userInput = bufferedReader.readLine()) != null) { System.out.println("Received from client: "+userInput); printWriter.println("Server responding with: "+userInput); //you can use your message to respond from server } System.out.println("Server stopped."); printWriter.close(); bufferedReader.close(); connectionSocket.close(); serverSocket.close();}} URL connections We have seen that to send or retrieve information to a web server, we use the HTTP protocol through a client socket attached to port 80 We can do this by using normal socket-based programming and sending the correct HTTP commands However, Java has specific support for the HTTP protocol through its URLConnection class Its very easy to retrieve a file from a web server by simply providing the files url as a string This sets up an input stream from a url connection Can turn this into a Scanner object for text processing The URLConnection class also has additional functionality related to the HTTP protocol Querying the server for header information Setting request properties
URL u=new URL(http://www.bham.ac.uk); URLConnection c=u.openConnection(); InputStream in=c.getInputStream(); The following simple example program opens a web page and displays the HTML It also checks the server response code 404 if the page is not found 200 if the connection succeeded Uses a Scanner object to output the lines of HTML public class URLGet { public static void main(String[] args) throws IOException {
// Read server response InputStream instream=httpConnection.getInputStream(); Scanner in=new Scanner(instream); while (in.hasNextLine()) { String input=in.nextLine(); System.out.println(input); } } } User Datagram Protocal(UDP) TCP includes many complicated algorithms for dealing with congestion control on crowded networks. Datagram provide an alternative. Datagrams are bundles of information passed between machines. They are somewhat like a hard throw from a well trained but blindfolded catcher to the third baseman. Java implements datagrams on top of the UDP by using two classes: DatagramSocket DatagramPacket DatagramPacket Class The object of this class hold the data which send on network. Constructor:- DatagramPacket(byte data[],int size) Receiving End DatagramPacket(byte data[],int offset,int size) DatagramPacket(byte data[],int size,InetAddress ipAddress, int port) DatagramPacket(byte data[],int offset,int size,InetAddress ipAddress, int port) Sending End
class UDPConnection{ public static int serverPort = 998; Server Application public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[]=new byte[buffer_size]; public static void TheServer() throws Exception{ int pos=0; System.out.println("Press Ctrl+C for exit"); while(true) { int c=System.in.read(); switch(c) { case -1: System.out.println("Server Quits."); return; case '\r': break; case '\n': ds.send(new DatagramPacket (buffer,pos, InetAddress. getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++] = (byte) c; } } }
Client Application
public static void TheClient() throws Exception { System.out.println("Press Ctrl+C for exit"); while(true) { DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); System.out.println(new String(p.getData(), 0 , p.getLength())); } }