SlideShare a Scribd company logo
1 of 20
Download to read offline
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

What's hot

Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Socketselliando dias
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programmingelliando dias
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Advanced Sockets Programming
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programmingelliando dias
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using CAjit Nayak
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming TutorialJignesh Patel
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 

What's hot (20)

Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Advanced Sockets Programming
Advanced Sockets ProgrammingAdvanced Sockets Programming
Advanced Sockets Programming
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Socket programming
Socket programming Socket programming
Socket programming
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
socket programming
socket programming socket programming
socket programming
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
Np unit2
Np unit2Np unit2
Np unit2
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 

Viewers also liked

Telshe Yeshiva - Teaching Future Generations in Cleveland
Telshe Yeshiva - Teaching Future Generations in ClevelandTelshe Yeshiva - Teaching Future Generations in Cleveland
Telshe Yeshiva - Teaching Future Generations in ClevelandLeib Tropper
 
традиции моей семьи. шоковы
традиции моей семьи. шоковытрадиции моей семьи. шоковы
традиции моей семьи. шоковыklepa.ru
 
Updated day 2 part 1 -social marketing basics training slides
Updated day 2 part 1 -social marketing basics training slidesUpdated day 2 part 1 -social marketing basics training slides
Updated day 2 part 1 -social marketing basics training slidesprogroup
 
Concept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-Intezaar
Concept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-IntezaarConcept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-Intezaar
Concept of Active Awaiting of Imam Mahdi (as) - Haqiqat-e-IntezaarSohel Ajani
 
5 mistakes in use of pronouns
5 mistakes in use of pronouns5 mistakes in use of pronouns
5 mistakes in use of pronounsSarwan Singh
 
Roi of online customer service communities
Roi of online customer service communitiesRoi of online customer service communities
Roi of online customer service communitiesCentrecom
 
Новости недвижимости Майами - Январь 2016
Новости недвижимости Майами - Январь 2016Новости недвижимости Майами - Январь 2016
Новости недвижимости Майами - Январь 2016The Reznik Group
 
Klimina anna
Klimina annaKlimina anna
Klimina annaklepa.ru
 
Medweb - Achievable Telemedicine Solutions in Afghanistan
Medweb - Achievable Telemedicine Solutions in AfghanistanMedweb - Achievable Telemedicine Solutions in Afghanistan
Medweb - Achievable Telemedicine Solutions in AfghanistanPeter Killcommons
 
3 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp01
3 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp013 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp01
3 1factorbygroupingandfactoringintoquadratics-120225222519-phpapp01Cikgu Shaiful Kisas
 
The Millennial Shift: Financial Services and the Digial Generation Study Preview
The Millennial Shift: Financial Services and the Digial Generation Study PreviewThe Millennial Shift: Financial Services and the Digial Generation Study Preview
The Millennial Shift: Financial Services and the Digial Generation Study PreviewCorporate Insight
 
Annuity and life insurance product update - Q2 2015
Annuity and life insurance product update - Q2 2015Annuity and life insurance product update - Q2 2015
Annuity and life insurance product update - Q2 2015Corporate Insight
 
Efimov vladislav
Efimov vladislavEfimov vladislav
Efimov vladislavklepa.ru
 
Adobe photoshop lesson by citra
Adobe photoshop lesson by citraAdobe photoshop lesson by citra
Adobe photoshop lesson by citraCitra Yoenita Mhd
 
Customer service presentation pdf Cert IV FLM
Customer service presentation pdf Cert IV FLMCustomer service presentation pdf Cert IV FLM
Customer service presentation pdf Cert IV FLMquandongpie
 
Environmental strategies workshop bouligny
Environmental strategies workshop boulignyEnvironmental strategies workshop bouligny
Environmental strategies workshop boulignyprogroup
 

Viewers also liked (18)

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

Similar to Lecture10

forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theoryMukesh Tekwani
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2Ankit Dubey
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 

Similar to Lecture10 (20)

Java adv
Java advJava adv
Java adv
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Java networking
Java networkingJava networking
Java networking
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Threads
ThreadsThreads
Threads
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Module 1 networking basics-2
Module 1   networking basics-2Module 1   networking basics-2
Module 1 networking basics-2
 
A.java
A.javaA.java
A.java
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Jnp
JnpJnp
Jnp
 

More from vantinhkhuc (20)

Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 

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