ADVANCED JAVA COMMUNICATION LABORATORY
Introduction to JavaJava is fully object-oriented language
The fastest growing programming language in the history of computing Developed by Sun Microsystems of USA in 1991 headed by James toslingJava is the first programming language that is not tied to any particular hardware or operating system.Java is Case sensitive language has rich collection of existing classes in java class libraries
Java Features 
Basic Concepts of JavaObjects and classes
Data abstraction
Date Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message PassingIntroduction to Java AppletA program written in the Java to run within a web browser.
Java applets begin execution with a series of init(), start(), and paint() methods. ;stop(), and destroy() methods are available.
Every Java applet should extend either class Japplet or class Applet.
Java applets are run from inside a World Wide Web browser
A single Java program can be written to operate as both a Java application and a Java applet.
An Example Programimport java.awt.*;import java.awt.event.*;import java.applet.*;public class Aman extends Applet implements ActionListener{Button b = new Button("Show message");TextField message = new TextField("", 15);public void init() {resize(300, 100);setBackground(Color.lightGray);b.addActionListener(this);add(b);message.setFont(new Font("Serif", Font.ITALIC, 24));message.setForeground(Color.red);7
message.setEditable(false);add(message);}public void actionPerformed(ActionEvent e) {if (message.getText().length() == 0) {message.setText("Hello world!");b.setLabel("Clear message");}else {message.setText("");b.setLabel("Show message");}}}
Including an Applet on a Web Page
Applet's Attributes31 October 2002Nelson Young11
What are the advantages of applets?Automatically integrated with HTML; hence, resolved virtually all installation issues.
Can be accessed from various platforms and various java-enabled web browsers.
Can provide dynamic, graphics capabilities and visualizations
Implemented in Java, an easy-to-learn OO programming languageNetwork Programming in Java
JAVA-NetworkingManipulating URL Establishing a simple ClientEstablishing a simple serverClient/Server Interaction with Socket Connection14
15Socket-based communicationSocket is an abstraction that facilitates communication between a server and a clientJava treats socket communications much as it treats I/O operationsThus, a program can read from a socket or write to a socket as simply as it can read from a file or writing to a file.Java support stream socket and datagram socketStream socket use TCP(Transmission Control Protocol)Datagram sockets use UDP(user datagram Protocol)
16Client-Server relationshipServer must be running when a client startsServer wait for a connection request from a clientAfter the sever accepts the connection, communication between the server and the client is conducted the same as for I/O streamsClient close the connectionServer can serve multiple clients
BSD Socket CallsNetworkServerClientsocket(): create socketsocket() : create socketbind() : name socketconnect(): listen() :accept(): accept connectionwrite() : send requestread() : get request.. . process request . . .write(): send replyread() : get reply17
18To establish a simple server1. Create a ServerSocket objectServerSocket server_socket = new ServerSocket(port, queuelength); the port identifies the TCP service on the socket. Port number between 0 and 1023 are reserved for privileged processes. For instance, email server run on 25, web server usually 802. The server waits for connection from clientSocket conn = server_socket.accept();
19To establish server-continued3. Get the OutputStream and InputStream objects that enable the server to communicate with the clientObjectInputStream in = new ObjectInputStream(conn.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());4. Processing phase: Server and client communicate via the InputStream (in) and OutputStream (out) objects5. When the transmission is complete, the server closes the connection by invoking the close method on the Socket.View code run server
20To establish a simple clientCreate a Socket to connect to the serversocket conn = new Socket(serverAddress, port);Socket methods getInputStream and getoutputStream are used to get references to the Socket associated InputStream and OutputStream.3. Processing phase: Client and server communicate via the InputStream and OutputStream objects.4. When transmission is complete, the client closes the connection by invoking the close method on the Socketview code run clientrun client
Multithreaded Programming in Java21
Threads of ExecutionEvery statement in a Java program is executed in a context called its thread of execution.
When you start a Java program in the normal way, the main() method—and any methods called from that method—are executed in a singled out (but otherwise ordinary) thread sometimes called the main thread.
Other threads can run concurrently with the main thread. These threads share access to the same classes and objects as the main thread, but they execute asynchronously, in their own time.
The main thread can create new threads; these threads can create further threads, etc.22

Java adv

  • 1.
    ADVANCED JAVACOMMUNICATION LABORATORY
  • 2.
    Introduction to JavaJavais fully object-oriented language
  • 3.
    The fastest growingprogramming language in the history of computing Developed by Sun Microsystems of USA in 1991 headed by James toslingJava is the first programming language that is not tied to any particular hardware or operating system.Java is Case sensitive language has rich collection of existing classes in java class libraries
  • 4.
  • 5.
    Basic Concepts ofJavaObjects and classes
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
    Message PassingIntroduction toJava AppletA program written in the Java to run within a web browser.
  • 12.
    Java applets beginexecution with a series of init(), start(), and paint() methods. ;stop(), and destroy() methods are available.
  • 13.
    Every Java appletshould extend either class Japplet or class Applet.
  • 14.
    Java applets arerun from inside a World Wide Web browser
  • 15.
    A single Javaprogram can be written to operate as both a Java application and a Java applet.
  • 16.
    An Example Programimportjava.awt.*;import java.awt.event.*;import java.applet.*;public class Aman extends Applet implements ActionListener{Button b = new Button("Show message");TextField message = new TextField("", 15);public void init() {resize(300, 100);setBackground(Color.lightGray);b.addActionListener(this);add(b);message.setFont(new Font("Serif", Font.ITALIC, 24));message.setForeground(Color.red);7
  • 17.
    message.setEditable(false);add(message);}public void actionPerformed(ActionEvente) {if (message.getText().length() == 0) {message.setText("Hello world!");b.setLabel("Clear message");}else {message.setText("");b.setLabel("Show message");}}}
  • 18.
    Including an Appleton a Web Page
  • 20.
  • 21.
    What are theadvantages of applets?Automatically integrated with HTML; hence, resolved virtually all installation issues.
  • 22.
    Can be accessedfrom various platforms and various java-enabled web browsers.
  • 23.
    Can provide dynamic,graphics capabilities and visualizations
  • 24.
    Implemented in Java,an easy-to-learn OO programming languageNetwork Programming in Java
  • 25.
    JAVA-NetworkingManipulating URL Establishinga simple ClientEstablishing a simple serverClient/Server Interaction with Socket Connection14
  • 26.
    15Socket-based communicationSocket isan abstraction that facilitates communication between a server and a clientJava treats socket communications much as it treats I/O operationsThus, a program can read from a socket or write to a socket as simply as it can read from a file or writing to a file.Java support stream socket and datagram socketStream socket use TCP(Transmission Control Protocol)Datagram sockets use UDP(user datagram Protocol)
  • 27.
    16Client-Server relationshipServer mustbe running when a client startsServer wait for a connection request from a clientAfter the sever accepts the connection, communication between the server and the client is conducted the same as for I/O streamsClient close the connectionServer can serve multiple clients
  • 28.
    BSD Socket CallsNetworkServerClientsocket():create socketsocket() : create socketbind() : name socketconnect(): listen() :accept(): accept connectionwrite() : send requestread() : get request.. . process request . . .write(): send replyread() : get reply17
  • 29.
    18To establish asimple server1. Create a ServerSocket objectServerSocket server_socket = new ServerSocket(port, queuelength); the port identifies the TCP service on the socket. Port number between 0 and 1023 are reserved for privileged processes. For instance, email server run on 25, web server usually 802. The server waits for connection from clientSocket conn = server_socket.accept();
  • 30.
    19To establish server-continued3.Get the OutputStream and InputStream objects that enable the server to communicate with the clientObjectInputStream in = new ObjectInputStream(conn.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());4. Processing phase: Server and client communicate via the InputStream (in) and OutputStream (out) objects5. When the transmission is complete, the server closes the connection by invoking the close method on the Socket.View code run server
  • 31.
    20To establish asimple clientCreate a Socket to connect to the serversocket conn = new Socket(serverAddress, port);Socket methods getInputStream and getoutputStream are used to get references to the Socket associated InputStream and OutputStream.3. Processing phase: Client and server communicate via the InputStream and OutputStream objects.4. When transmission is complete, the client closes the connection by invoking the close method on the Socketview code run clientrun client
  • 32.
  • 33.
    Threads of ExecutionEverystatement in a Java program is executed in a context called its thread of execution.
  • 34.
    When you starta Java program in the normal way, the main() method—and any methods called from that method—are executed in a singled out (but otherwise ordinary) thread sometimes called the main thread.
  • 35.
    Other threads canrun concurrently with the main thread. These threads share access to the same classes and objects as the main thread, but they execute asynchronously, in their own time.
  • 36.
    The main threadcan create new threads; these threads can create further threads, etc.22
  • 37.
    Creating New ThreadsAnyJava thread of execution (including the main thread) is associated with an instance of the Thread class. Before starting a new thread, you must create a new instance of this class.
  • 38.
    The Java Threadclass implements the interface Runnable. So every Thread instance has a method: public void run() { . . . }When the thread is started, the code executed in the new thread is the body of the run() method.
  • 39.
    Generally speaking thenew thread ends when this method returns.23
  • 40.
    Making Thread InstancesThereare two ways to create a thread instance (and define the thread run() method).Extend the Thread class and override the run() method, e.g.:class MyThreadextends Thread { public void run() {System.out.println(“Hello from another thread”) ; }}. . .Thread thread = new MyThread() ;Create a separate Runnable object and pass to the Thread constructor:class MyRunnableimplements Runnable { public void run() {System.out.println(“Hello from another thread”) ; }}. . .Thread thread = new MyThread(new MyRunnable()) ;24
  • 41.
    Starting a ThreadCreatingthe Thread instance does not in itself start the thread running.
  • 42.
    To do thatyou must call the start() method on the new instance:thread.start() ; This operation causes the run() method to start executing concurrently with the original thread.In our example the new thread will print the message “Hello from another thread” to standard output, then immediately terminate.
  • 43.
    You can onlycall the start() method once on any Thread instance. Trying to “restart” a thread causes an exception to be thrown.25
  • 44.
    Example: Multiple ThreadsclassMyThread extends Thread { MyThread(int id) { this.id = id ; }public void run() { System.out.println(“Hello from thread ” + id) ; } private int id ;}. . .Thread [] threads = new Thread [p] ;for(int i = 0 ; i < p ; i++) threads [i] = new MyThread(i) ;for(int i = 0 ; i < p ; i++) threads [i].start() ;26
  • 45.
    RemarksThis is oneway of creating and starting p new threads to run concurrently.
  • 46.
    The output mightbe something like (for p = 4): Hello from thread 3 Hello from thread 4 Hello from thread 2 Hello from thread 1There is no guarantee of order (or atomicity) of outputs, because the threads are concurrent.One might worry about the efficiency of this approach for large numbers of threads (massive parallelism).27
  • 47.
    UDP in JavaTheUser Datagram Protocol is an alternative for TCP Socket which is neither connection-oriented nor “reliable”.It transports datagrams: messages of fixed (limited) size.
  • 48.
    Messages may occasionallybe lost; they may also be delivered out of order.
  • 49.
    But for applicationsthat don’t need strong guarantees it can be faster than TCP, e.g. the Internet Domain Naming Service is implemented over UDP.
  • 50.
    Finally, you haveto use UDP if you want to exploit IP multicast.28
  • 51.
    AUDP Message Producerimportjava.net.* ;public class UDPProducer { public static void main(String [] args) throws java.io.IOException {DatagramSocket sock = new DatagramSocket() ;InetAddressaddr = InetAddress.getByName("grids.ucs.indiana.edu") ;int port = 3516 ; for(inti = 0 ; i < 10 ; i++) { String message = "message " + i ; byte [] data = message.getBytes() ;DatagramPacket packet = new DatagramPacket(data, data.length, addr, port) ;sock.send(packet) ; } }}29
  • 52.
    A UDP MessageConsumerimport java.net.* ;public class UDPConsumer { public static void main(String [] args) throws java.io.IOException {int port = 3516 ;DatagramSocket sock = new DatagramSocket(port) ; byte [] buffer = new byte [65536] ; while(true) {DatagramPacket packet = new DatagramPacket(buffer, buffer.length) ;sock.receive(packet) ; String message = new String(packet.getData(), 0, packet.getLength()) ;System.out.println(message) ; } }}30
  • 53.
    What is aservlet?A servlet is a Java program that executes in a special secure environment, such as
  • 54.
  • 55.
  • 56.
    Commonly run insidea web server, servlets are dynamically loaded to extend the functionality of the server
  • 57.
    Functionally, servlets isan alternative to CGI scripts for creating dynamic web content An interface that all servlets must implementVoid init(ServletConfigconfig)Called every time the servlet is instantiatedVoid service(ServletRequestreq, ServletResponse res)ServletRequest: parameters from the clientServletResponse: contains an output stream used to return information to the clientNeeds to be thread-safe since multiple requests can be handled concurrentlyNot called until init() has finished execution
  • 58.
    void destroy()called bythe servlet engine when it removes the servletshould free any resources (i.e. files or database connections) held by the servletString getServletInfo()Returns version and copyright information
  • 59.
  • 60.
    Receives requests andsends responses to a web browser
  • 61.
    Methods to handledifferent types of HTTP requests:
  • 62.
  • 63.
  • 64.
  • 65.
    doDelete() handles DELETErequestsWhat are the advantages of servlets?Portabilitywrite once, serve everywherePowercan take advantage of all core Java APIsElegancesimplicity due to abstractionEfficiency & Enduranceinstance persistence, highly scalable=
  • 66.