SlideShare a Scribd company logo
TCP Sockets
But first ...
 Background on Threads
Multithreading
Overview of Multithreading in Java
  Java has build-in support for concurrent
  programming. This enables you to have
  multiple flows of control, represented by
  multiple threads within a single program
  (process).
    A thread is a single sequential flow of control
    within a process.
    Each thread has a separate execution path, with
    its own beginning, program flow, current point of
    execution, and end.
    They are represented by Thread objects in Java.
Multithreading (Contd.)
  Multithreading allows a program to perform
  multiple tasks concurrently.
    Although threads give the appearance of running
    concurrently, in a single p
                            - rocessor system the
    interpreter is switching between the threads and
    running them one at a time.
    Multiprocessor systems may actually run multiple
    threads concurrently.
    The threads all run in the same memory space,
    i.e., they can all access the same memory and call
    methods as if they were in a normal single-
    threaded process.
Why Threads?
 Threads are useful whenever you have
 multiple tasks that you want to run
 concurrently.
   For example, consider a program that
   interactively reacts with the user, and that
   also needs to download a file over the
   networks.
The Thread Class
 You create and manipulate threads in Java using instances of the Thread
 class.
    One way to use threads is to subclass Thread, and override its run() method.
    The run() method is the heart of the Thread object. It should contain code to do
    whatever work the object needs to do.

  class FileDownload extends Thread
  {
     public void run()
     {
       // code to download file
     }
  }

 The Thread class in defines in java.lang package.
Creating Threads
 Creating the thread is done by creating an instance of the new class.
    You then invoke the start() method, inherited from Thread.
    start() automatically invokes run(), and then returns control
    immediately.
    run() will now execute in a separate thread.

  FileDownload fd = new FileDownload();
  fd.start();            // Returns control immediately
  // Do whatever else you want to do
  // e.g., continue to interact with user

 The new thread runs until its run() method finishes, or until you stop
 it explicitly.
The Runnable Interface
 You can also use classes that implement the Runnable interface to run code in
 separate threads.
      The Runnable interface simply declares the run() method. It is also defined in the java.lang
      package.
  class FileDownload implements Runnable
  {
      public void run()
      {
        // Code to download file
      }
  }
 To run the code is a separate thread, create an instance of Thread, with an instance
 of the Runnable as an argument to its constructor.
 Starting the thread with then cause the Runnable’s run() method to be executed.
  Thread t = new Thread( new FileDownload() );
  t.start();                 // Calls FileDownload’s run() method
 This allows to have code executed in a thread without needing to subclass
 Thread. This is useful if you need to subclass a different class to get other
 functionality (e.g., the Applet class).
A Simple Example
// Define a class that extends Thread
class LoopThread extends Thread
{
    // Define its run() method to do what you want
    public void run()
    {
            for(int i=1; i <= 20; i++) System.out.println(“I am loopy”);
    }
}

public class Looper
{
    public static void main(String[] args)
    {
            // Create an instance of the thread
            LoopThread loopy = new LoopThread();

            // Start it up
            loopy.start();
    }
}
TCP Sockets
JAVA - Internet Addresses
 java.net.InetAddress class

 You get an address by using static methods:
 Create InetAddress object representing the local machine
  InetAddress myAddress = InetAddress.getLocalHost();

 Create InetAddress object representing some remote machine
  InetAddress ad = InetAddress.getByName(hostname);
JAVA - Printing Internet Addresses

 You get information from an InetAddress
 by using methods:

 ad.getHostName();
 ad.getHostAddress();
JAVA - The InetAddress Class
Handles Internet addresses both as host names and as IP addresses
Static Method getByName returns the IP address of a specified host name as an InetAddress
object
Methods for address/name conversion:
 public static InetAddress getByName(String host) throws UnknownHostException
 public static InetAddress[] getAllByName(String host) throws UnknownHostException
 public static InetAddress getLocalHost() throws UnknownHostException

 public boolean isMulticastAddress()
 public String getHostName()
 public byte[] getAddress()
 public String getHostAddress()
 public int hashCode()
 public boolean equals(Object obj)
 public String toString()
The Java.net.Socket Class

Connection is accomplished through the constructors. Each Socket object is
associated with exactly one remote host. To connect to a different host, you
must create a new Socket object.
     public Socket(String host, int port) throws UnknownHostException, IOException
     public Socket(InetAddress address, int port) throws IOException
     public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
     public Socket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException

Sending and receiving data is accomplished with output and input streams.
There are methods to get an input stream for a socket and an output stream for
the socket.
      public InputStream getInputStream() throws IOException
      public OutputStream getOutputStream() throws IOException

There is a method to close a socket:
     public void close() throws IOException
The Java.net.ServerSocket Class
The java.net.ServerSocket class represents a server
socket. It is constructed on a particular port. Then it calls
accept() to listen for incoming connections.
   accept() blocks until a connection is detected.
   Then accept() returns a java.net.Socket object that is used to
   perform the actual communication with the client.

   public ServerSocket(int port) throws IOException
   public ServerSocket(int port, int backlog) throws IOException
   public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException


   public Socket accept() throws IOException                    [BLOCKING]
   public void close() throws IOException
TCP Sockets
SERVER:
1. Create a ServerSocket object
     ServerSocket servSocket = new ServerSocket(1234);
2.   Put the server into a waiting state
     Socket link = servSocket.accept();    //BLOCKING

3.   Set up input and output streams
4.   Send and receive data
     out.println(data);
     String input = in.readLine();
5.   Close the connection
     link.close()
Set up input and output streams
 Once a socket has connected you send data to
 the server via an output stream. You receive data
 from the server via an input stream.
 Methods getInputStream and getOutputStream of
 class Socket:
 BufferedReader in =
     new BufferedReader(
 new InputStreamReader(link.getInputStream()));

 PrintWriter out =
     new PrintWriter(link.getOutputStream(),true);
TCP Sockets
CLIENT:
1. Establish a connection to the server
     Socket link =
     new Socket(inetAddress.getLocalHost(), 1234);
2.   Set up input and output streams
3.   Send and receive data
4.   Close the connection
References
 Cisco Networking Academy Program (CCNA), Cisco Press.

 CSCI-5273 : Computer Networks, Dirk Grunwald, University of Colorado-Boulder

 CSCI-4220: Network Programming, Dave Hollinger, Rensselaer Polytechnic Institute.

 TCP/IP Illustrated, Volume 1, Stevens.

 Java Network Programming and Distributed Computing, Reilly & Reilly.

 Computer Networks: A Systems Approach, Peterson & Davie.

 http://www.firewall.cx

 http://www.javasoft.com

More Related Content

PDF
Network Sockets
PPTX
IPC SOCKET
PPT
Socket System Calls
PPT
Sockets in unix
PDF
PPTX
Elementary TCP Sockets
PPTX
Socket programming
PPTX
Socket programming
Network Sockets
IPC SOCKET
Socket System Calls
Sockets in unix
Elementary TCP Sockets
Socket programming
Socket programming

What's hot (20)

PDF
Programming TCP/IP with Sockets
PPT
Application Layer and Socket Programming
PPT
Basic socket programming
PPT
Socket programming
PPT
Ppt of socket
PPTX
Socket Programming
PDF
Advanced Sockets Programming
PDF
Socket programming using C
PDF
Socket Programming
PPT
Tcp sockets
PPTX
Socket programming in c
PDF
Socket programming
PPT
Socket programming-tutorial-sk
PPTX
Socket programming
PPT
Socket Programming Tutorial
DOC
socket programming
PPT
Socket programming in C
PPT
Np unit2
PDF
Socket programming using java
PPT
Java Socket Programming
Programming TCP/IP with Sockets
Application Layer and Socket Programming
Basic socket programming
Socket programming
Ppt of socket
Socket Programming
Advanced Sockets Programming
Socket programming using C
Socket Programming
Tcp sockets
Socket programming in c
Socket programming
Socket programming-tutorial-sk
Socket programming
Socket Programming Tutorial
socket programming
Socket programming in C
Np unit2
Socket programming using java
Java Socket Programming
Ad

Viewers also liked (18)

PPTX
Telshe Yeshiva - Teaching Future Generations in Cleveland
PPTX
традиции моей семьи. шоковы
PPT
Updated day 2 part 1 -social marketing basics training slides
PPTX
Concept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-Intezaar
PDF
5 mistakes in use of pronouns
PDF
Roi of online customer service communities
PPTX
Новости недвижимости Майами - Январь 2016
PPTX
Klimina anna
PPTX
Medweb - Achievable Telemedicine Solutions in Afghanistan
PPT
3 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp01
PDF
The Millennial Shift: Financial Services and the Digial Generation Study Preview
DOCX
Health and wellness
PDF
PPTX
Annuity and life insurance product update - Q2 2015
PPTX
Efimov vladislav
PPTX
Adobe photoshop lesson by citra
PDF
Customer service presentation pdf Cert IV FLM
PPT
Environmental strategies workshop bouligny
Telshe Yeshiva - Teaching Future Generations in Cleveland
традиции моей семьи. шоковы
Updated day 2 part 1 -social marketing basics training slides
Concept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-Intezaar
5 mistakes in use of pronouns
Roi of online customer service communities
Новости недвижимости Майами - Январь 2016
Klimina anna
Medweb - Achievable Telemedicine Solutions in Afghanistan
3 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp01
The Millennial Shift: Financial Services and the Digial Generation Study Preview
Health and wellness
Annuity and life insurance product update - Q2 2015
Efimov vladislav
Adobe photoshop lesson by citra
Customer service presentation pdf Cert IV FLM
Environmental strategies workshop bouligny
Ad

Similar to Lecture10 (20)

PPTX
advanced java ppt
PDF
Jnp
PDF
Java Programming - 08 java threading
PDF
Java networking programs - theory
PDF
How a network connection is created A network connection is initi.pdf
PDF
17-Networking.pdf
PPT
Socket Programming in Java.ppt yeh haii
PPTX
Multithreading.pptx
DOCX
Please look at the attach See.doc. I am getting this error all th.docx
PPT
Networking & Socket Programming In Java
PPT
Sockets
PPT
web programming-Multithreading concept in Java.ppt
PPTX
Multithreading in java
PPT
PPT
Unit 8 Java
PPTX
Advance Java-Network Programming
PDF
Ppl for students unit 4 and 5
PDF
Ppl for students unit 4 and 5
PPT
Threads in java, Multitasking and Multithreading
advanced java ppt
Jnp
Java Programming - 08 java threading
Java networking programs - theory
How a network connection is created A network connection is initi.pdf
17-Networking.pdf
Socket Programming in Java.ppt yeh haii
Multithreading.pptx
Please look at the attach See.doc. I am getting this error all th.docx
Networking & Socket Programming In Java
Sockets
web programming-Multithreading concept in Java.ppt
Multithreading in java
Unit 8 Java
Advance Java-Network Programming
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
Threads in java, Multitasking and Multithreading

More from vantinhkhuc (20)

PDF
Url programming
PDF
Servlets intro
PDF
Servlet sessions
PDF
Security overview
PDF
PDF
PDF
Lecture17
PDF
Lecture11 b
PDF
Lecture9
PDF
Lecture6
PDF
PDF
Jsf intro
PDF
Jsp examples
PDF
PDF
Ejb examples
PDF
PDF
PDF
Ejb intro
PPT
Chc6b0c6a1ng 12
PPT
Url programming
Servlets intro
Servlet sessions
Security overview
Lecture17
Lecture11 b
Lecture9
Lecture6
Jsf intro
Jsp examples
Ejb examples
Ejb intro
Chc6b0c6a1ng 12

Lecture10

  • 2. But first ... Background on Threads
  • 4. Overview of Multithreading in Java Java has build-in support for concurrent programming. This enables you to have multiple flows of control, represented by multiple threads within a single program (process). A thread is a single sequential flow of control within a process. Each thread has a separate execution path, with its own beginning, program flow, current point of execution, and end. They are represented by Thread objects in Java.
  • 5. Multithreading (Contd.) Multithreading allows a program to perform multiple tasks concurrently. Although threads give the appearance of running concurrently, in a single p - rocessor system the interpreter is switching between the threads and running them one at a time. Multiprocessor systems may actually run multiple threads concurrently. The threads all run in the same memory space, i.e., they can all access the same memory and call methods as if they were in a normal single- threaded process.
  • 6. Why Threads? Threads are useful whenever you have multiple tasks that you want to run concurrently. For example, consider a program that interactively reacts with the user, and that also needs to download a file over the networks.
  • 7. The Thread Class You create and manipulate threads in Java using instances of the Thread class. One way to use threads is to subclass Thread, and override its run() method. The run() method is the heart of the Thread object. It should contain code to do whatever work the object needs to do. class FileDownload extends Thread { public void run() { // code to download file } } The Thread class in defines in java.lang package.
  • 8. Creating Threads Creating the thread is done by creating an instance of the new class. You then invoke the start() method, inherited from Thread. start() automatically invokes run(), and then returns control immediately. run() will now execute in a separate thread. FileDownload fd = new FileDownload(); fd.start(); // Returns control immediately // Do whatever else you want to do // e.g., continue to interact with user The new thread runs until its run() method finishes, or until you stop it explicitly.
  • 9. The Runnable Interface You can also use classes that implement the Runnable interface to run code in separate threads. The Runnable interface simply declares the run() method. It is also defined in the java.lang package. class FileDownload implements Runnable { public void run() { // Code to download file } } To run the code is a separate thread, create an instance of Thread, with an instance of the Runnable as an argument to its constructor. Starting the thread with then cause the Runnable’s run() method to be executed. Thread t = new Thread( new FileDownload() ); t.start(); // Calls FileDownload’s run() method This allows to have code executed in a thread without needing to subclass Thread. This is useful if you need to subclass a different class to get other functionality (e.g., the Applet class).
  • 10. A Simple Example // Define a class that extends Thread class LoopThread extends Thread { // Define its run() method to do what you want public void run() { for(int i=1; i <= 20; i++) System.out.println(“I am loopy”); } } public class Looper { public static void main(String[] args) { // Create an instance of the thread LoopThread loopy = new LoopThread(); // Start it up loopy.start(); } }
  • 12. JAVA - Internet Addresses java.net.InetAddress class You get an address by using static methods: Create InetAddress object representing the local machine InetAddress myAddress = InetAddress.getLocalHost(); Create InetAddress object representing some remote machine InetAddress ad = InetAddress.getByName(hostname);
  • 13. JAVA - Printing Internet Addresses You get information from an InetAddress by using methods: ad.getHostName(); ad.getHostAddress();
  • 14. JAVA - The InetAddress Class Handles Internet addresses both as host names and as IP addresses Static Method getByName returns the IP address of a specified host name as an InetAddress object Methods for address/name conversion: public static InetAddress getByName(String host) throws UnknownHostException public static InetAddress[] getAllByName(String host) throws UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException public boolean isMulticastAddress() public String getHostName() public byte[] getAddress() public String getHostAddress() public int hashCode() public boolean equals(Object obj) public String toString()
  • 15. The Java.net.Socket Class Connection is accomplished through the constructors. Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object. public Socket(String host, int port) throws UnknownHostException, IOException public Socket(InetAddress address, int port) throws IOException public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException public Socket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException Sending and receiving data is accomplished with output and input streams. There are methods to get an input stream for a socket and an output stream for the socket. public InputStream getInputStream() throws IOException public OutputStream getOutputStream() throws IOException There is a method to close a socket: public void close() throws IOException
  • 16. The Java.net.ServerSocket Class The java.net.ServerSocket class represents a server socket. It is constructed on a particular port. Then it calls accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept() returns a java.net.Socket object that is used to perform the actual communication with the client. public ServerSocket(int port) throws IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException public Socket accept() throws IOException [BLOCKING] public void close() throws IOException
  • 17. TCP Sockets SERVER: 1. Create a ServerSocket object ServerSocket servSocket = new ServerSocket(1234); 2. Put the server into a waiting state Socket link = servSocket.accept(); //BLOCKING 3. Set up input and output streams 4. Send and receive data out.println(data); String input = in.readLine(); 5. Close the connection link.close()
  • 18. Set up input and output streams Once a socket has connected you send data to the server via an output stream. You receive data from the server via an input stream. Methods getInputStream and getOutputStream of class Socket: BufferedReader in = new BufferedReader( new InputStreamReader(link.getInputStream())); PrintWriter out = new PrintWriter(link.getOutputStream(),true);
  • 19. TCP Sockets CLIENT: 1. Establish a connection to the server Socket link = new Socket(inetAddress.getLocalHost(), 1234); 2. Set up input and output streams 3. Send and receive data 4. Close the connection
  • 20. References Cisco Networking Academy Program (CCNA), Cisco Press. CSCI-5273 : Computer Networks, Dirk Grunwald, University of Colorado-Boulder CSCI-4220: Network Programming, Dave Hollinger, Rensselaer Polytechnic Institute. TCP/IP Illustrated, Volume 1, Stevens. Java Network Programming and Distributed Computing, Reilly & Reilly. Computer Networks: A Systems Approach, Peterson & Davie. http://www.firewall.cx http://www.javasoft.com