SlideShare a Scribd company logo
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
Java adv
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

More Related Content

What's hot (20)

PDF
Java Multithreading Using Executors Framework
Arun Mehra
 
ODP
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
PPTX
Multi Threading
Ferdin Joe John Joseph PhD
 
PPTX
Java concurrency - Thread pools
maksym220889
 
PPT
Java multi threading
Raja Sekhar
 
PPTX
Basics of Java Concurrency
kshanth2101
 
PPTX
Concurrency in Java
Allan Huang
 
PDF
Multithreading in Java
Appsterdam Milan
 
PPTX
Multithread Programing in Java
M. Raihan
 
PDF
Android development training programme , Day 3
DHIRAJ PRAVIN
 
PPT
Java Threads and Concurrency
Sunil OS
 
PPTX
Multithreading in java
junnubabu
 
PDF
Java Concurrency in Practice
Alina Dolgikh
 
PPTX
Threading in C#
Medhat Dawoud
 
PPTX
Effective java - concurrency
feng lee
 
PPTX
Threading
abhay singh
 
PPS
Java session13
Niit Care
 
PPT
Tech talk
Preeti Patwa
 
PPTX
Multi-threaded Programming in JAVA
Vikram Kalyani
 
PPTX
Java Thread & Multithreading
jehan1987
 
Java Multithreading Using Executors Framework
Arun Mehra
 
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Java concurrency - Thread pools
maksym220889
 
Java multi threading
Raja Sekhar
 
Basics of Java Concurrency
kshanth2101
 
Concurrency in Java
Allan Huang
 
Multithreading in Java
Appsterdam Milan
 
Multithread Programing in Java
M. Raihan
 
Android development training programme , Day 3
DHIRAJ PRAVIN
 
Java Threads and Concurrency
Sunil OS
 
Multithreading in java
junnubabu
 
Java Concurrency in Practice
Alina Dolgikh
 
Threading in C#
Medhat Dawoud
 
Effective java - concurrency
feng lee
 
Threading
abhay singh
 
Java session13
Niit Care
 
Tech talk
Preeti Patwa
 
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Java Thread & Multithreading
jehan1987
 

Similar to Java adv (20)

PDF
Lecture10
vantinhkhuc
 
PPT
Sockets
sivindia
 
DOCX
forwarder.java.txt java forwarder class waits for an in.docx
budbarber38650
 
PDF
Jnp
hj43us
 
PDF
28 networking
Ravindra Rathore
 
PPT
Socket Programming - nitish nagar
Nitish Nagar
 
PPTX
A.java
JahnaviBhagat
 
PDF
Java networking programs - theory
Mukesh Tekwani
 
PPTX
advanced java ppt
PreetiDixit22
 
PPT
MULTITHREADING CONCEPT
RAVI MAURYA
 
PPT
Multi user chat system using java
Akhil Goutham Kotini
 
PDF
04 android
guru472
 
PPT
Basic java part_ii
Khaled AlGhazaly
 
PPT
9.multi-threading latest(MB).ppt .
happycocoman
 
PDF
Threads
saanchi85
 
PDF
Core Java Programming Language (JSE) : Chapter XII - Threads
WebStackAcademy
 
PPTX
Network programming in java - PPT
kamal kotecha
 
DOCX
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
PPTX
Thread syncronization
priyabogra1
 
PPTX
Advance Java-Network Programming
ashok hirpara
 
Lecture10
vantinhkhuc
 
Sockets
sivindia
 
forwarder.java.txt java forwarder class waits for an in.docx
budbarber38650
 
Jnp
hj43us
 
28 networking
Ravindra Rathore
 
Socket Programming - nitish nagar
Nitish Nagar
 
Java networking programs - theory
Mukesh Tekwani
 
advanced java ppt
PreetiDixit22
 
MULTITHREADING CONCEPT
RAVI MAURYA
 
Multi user chat system using java
Akhil Goutham Kotini
 
04 android
guru472
 
Basic java part_ii
Khaled AlGhazaly
 
9.multi-threading latest(MB).ppt .
happycocoman
 
Threads
saanchi85
 
Core Java Programming Language (JSE) : Chapter XII - Threads
WebStackAcademy
 
Network programming in java - PPT
kamal kotecha
 
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
Thread syncronization
priyabogra1
 
Advance Java-Network Programming
ashok hirpara
 
Ad

More from Balakumaran Arunachalam (10)

PPT
Campus deck
Balakumaran Arunachalam
 
PPT
visible surface detection
Balakumaran Arunachalam
 
PPT
Greenhouse effect
Balakumaran Arunachalam
 
PPT
Career path non technical
Balakumaran Arunachalam
 
ODP
Installing and configuring apache
Balakumaran Arunachalam
 
ODP
Tags in html
Balakumaran Arunachalam
 
ODP
Sql installation
Balakumaran Arunachalam
 
ODP
Sql commands
Balakumaran Arunachalam
 
ODP
Linux commands
Balakumaran Arunachalam
 
visible surface detection
Balakumaran Arunachalam
 
Greenhouse effect
Balakumaran Arunachalam
 
Career path non technical
Balakumaran Arunachalam
 
Installing and configuring apache
Balakumaran Arunachalam
 
Sql installation
Balakumaran Arunachalam
 
Linux commands
Balakumaran Arunachalam
 
Ad

Recently uploaded (20)

PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 

Java adv

  • 1. ADVANCED JAVA COMMUNICATION LABORATORY
  • 2. Introduction to JavaJava is fully object-oriented language
  • 3. 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
  • 5. Basic Concepts of JavaObjects and classes
  • 11. Message PassingIntroduction to Java AppletA program written in the Java to run within a web browser.
  • 12. Java applets begin execution with a series of init(), start(), and paint() methods. ;stop(), and destroy() methods are available.
  • 13. Every Java applet should extend either class Japplet or class Applet.
  • 14. Java applets are run from inside a World Wide Web browser
  • 15. A single Java program can be written to operate as both a Java application and a Java applet.
  • 16. 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
  • 17. 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");}}}
  • 18. Including an Applet on a Web Page
  • 20. Applet's Attributes31 October 2002Nelson Young11
  • 21. What are the advantages of applets?Automatically integrated with HTML; hence, resolved virtually all installation issues.
  • 22. Can be accessed from 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 Establishing a simple ClientEstablishing a simple serverClient/Server Interaction with Socket Connection14
  • 26. 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)
  • 27. 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
  • 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 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();
  • 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 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
  • 33. Threads of ExecutionEvery statement in a Java program is executed in a context called its thread of execution.
  • 34. 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.
  • 35. 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.
  • 36. The main thread can create new threads; these threads can create further threads, etc.22
  • 37. Creating New ThreadsAny Java 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 Thread class 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 the new thread ends when this method returns.23
  • 40. Making Thread InstancesThere are 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 ThreadCreating the Thread instance does not in itself start the thread running.
  • 42. To do that you 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 only call the start() method once on any Thread instance. Trying to “restart” a thread causes an exception to be thrown.25
  • 44. Example: Multiple Threadsclass MyThread 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 one way of creating and starting p new threads to run concurrently.
  • 46. The output might be 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 JavaThe User 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 occasionally be lost; they may also be delivered out of order.
  • 49. But for applications that 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 have to use UDP if you want to exploit IP multicast.28
  • 51. AUDP Message Producerimport java.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 Message Consumerimport 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 a servlet?A servlet is a Java program that executes in a special secure environment, such as
  • 56. Commonly run inside a web server, servlets are dynamically loaded to extend the functionality of the server
  • 57. Functionally, servlets is an 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 by the 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
  • 60. Receives requests and sends responses to a web browser
  • 61. Methods to handle different types of HTTP requests:
  • 65. doDelete() handles DELETE requestsWhat are the advantages of servlets?Portabilitywrite once, serve everywherePowercan take advantage of all core Java APIsElegancesimplicity due to abstractionEfficiency & Enduranceinstance persistence, highly scalable=