SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
SOCKET PROGRAMMING IN JAVA



             Narendran Thangarajan,
             @naren_live,
             II Year, BE, CSE,
             SSN College of Engg, Chennai.
What started it all..
 Internet has emerged as a global ubiquitous
  media for communication

 It has changed the way we live, learn, enjoy,
  communicate, interact, engage, etc.

 To take advantage of this, businesses are
  ceaselessly trying to offer their services through
  the internet.

 So a huge demand for software developers good
  in creating internet-enabled applications.
Client Server Applications

        The Web Service is provided by the server
        and the clients use these services


   Client
                                             Server
                        Network


Client machine
                                       Server machine
        A client, where sockets and network
            This is
                    A server, come in !!
Sockets
 Introduced in BSD 4.1 UNIX 1981.


 Sockets are the endpoints of any
  communication over the internet.

 Sockets are identified by socket addresses.


 Socket Address = IP Address + Port Number
Why IP Address + Port number?
 • IP Address is of the form 10.0.0.1

 • Port Number can be anything from 0 to 65,535.
Destination Socket = 10.0.0.2 : 80

IP Address – Choose network

                      20.0.0.0



     10.0.0.0                     30.0.0.0




                       40.0.0.0
Destination Socket = 10.0.0.2 : 80


IP Address -> MAC Address – Locate the
                          specific system



            10.0.0.1

        10.0.0.2
Port Number – Process specific
Port 10000



                           Port 11000




                         Port 120000
Understanding Ports

         OutLook             AVG
Gmail               YM
         Express            Update




Port 1    Port 2   Port 3   Port 4

          Transport Layer
                                         Packet

                                         Port num    data


                                     Network layer
 Thus virtually, sockets are a connection
  between the two processes in different
  systems.

 Eg : Let the socket pairs be
   10.0.0.1 : 80 and 20.0.0.1 : 2000
   192.168.21.10 : 3000 and 192.168.100.1 : 6000
Networking Basics – the larger picture

     Applications Layer
       Standard apps
         HTTP             TCP STACK
         FTP
         Telnet               Application
       User apps          (http,ftp,telnet,…)
     Transport Layer           Transport
       TCP                   (TCP, UDP,..)
       UDP
                                Network
     Network Layer              (IP,..)
       IP
     Link Layer                  Link
                            (device driver,..)
       Device drivers
Network Basics - Where are these sockets?

      Applications Layer
          Standard apps
            HTTP              TCP STACK
            FTP
            Telnet                Application
          User apps           (http,ftp,telnet,…)


     Programming Interface:      Sockets
          SOCKETS

                                    Transport
      Transport Layer            (TCP, UDP,..)
          TCP
          UDP                      Network
                                     (IP,..)
        Network Layer                Link
            IP
        Link Layer
                                (device driver,..)
            Device drivers
Now into Socket
 programming..
Socket Programming with TCP
 Server starts first..
   Server Process must be running first
   Server must have created a socket which welcomes
     client’s connection. (Welcoming socket)
 Client contacts server by..
   Creating Client local TCP socket
   Specify IP Address and port number of server process.
   When Client socket is created, the connection is
    established.
   When connection is established, server creates a new
    socket (Connection Socket) to communicate with that
    client and the Welcoming socket is once again waiting
    for connections for other clients.
Client/Server Socket Interaction in
TCP
       Server
     create socket,
     port=x, for
     incoming request:
     welcomeSocket =
         ServerSocket()                          Client
     wait for incoming
                          TCP                create socket,
     connection request   connection setup   connect to hostid, port=x
     connectionSocket =                      clientSocket =
     welcomeSocket.accept()                         Socket()

                                               send request using
     read request from                         clientSocket
     connectionSocket

     write reply to
     connectionSocket                          read reply from
                                               connectionSocket
     close
     connectionSocket                           close
                                                clientSocket
Step 1 :
                        Connection request
            port
   Server
                                                    Client




Step 2 :
             port




   Server




                                             port
                                                    Client
    port            Connection
Types of Sockets in TCP

 ServerSocket – the socket used by servers
 Socket – Socket used by clients


 Create a ServerSocket in the server and make
  it to wait for connections from Sockets from
  other clients
The concept of Streams
       Client output    Server input
       stream           stream



     Client              Server
     socket              socket




    Client input       Server output
    stream             stream
Socket Programming with UDP

 No Connection between client and server.
   No handshaking
   The sender has to explicitly mention the IP
    address and the port of the destination.
   The server should extract the IP Address of the
    datagram everytime.


 Uses DatagramSocket.
Client/server socket interaction:
UDP
   Server                   Client
  create socket,       create socket,
  port=x, for          clientSocket =
  incoming request:    DatagramSocket()
  serverSocket =
  DatagramSocket()
                       Create, address (hostid, port=x),
                       send datagram request
                       using clientSocket
   read request from
   serverSocket

   write reply to
   serverSocket
                        read reply from
   specifying client
                        clientSocket
   host address,
   port number           close
                         clientSocket
Coding time..
Conclusion

 Socket Programming is very easy in Java.


 Usually each and every socket is handled by a
  separate thread in real-time client/server
  environments.
Queries

Contenu connexe

Tendances

Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
What is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaWhat is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaEdureka!
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming TutorialJignesh Patel
 
Socket Programming
Socket ProgrammingSocket Programming
Socket ProgrammingCEC Landran
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 

Tendances (20)

Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
What is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaWhat is Socket Programming in Python | Edureka
What is Socket Programming in Python | Edureka
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java rmi
Java rmiJava rmi
Java rmi
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java threading
Java threadingJava threading
Java threading
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Servlets
ServletsServlets
Servlets
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Servlets
ServletsServlets
Servlets
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java IO
Java IOJava IO
Java IO
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 

Similaire à Socket programming using java

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 
Socket Programming_theory.ppt
Socket Programming_theory.pptSocket Programming_theory.ppt
Socket Programming_theory.pptmdrobinhossain4
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 
Understanding computer networks
Understanding computer networksUnderstanding computer networks
Understanding computer networksUC San Diego
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23Techvilla
 

Similaire à Socket programming using java (20)

Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Client server project
Client server projectClient server project
Client server project
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Sockets
SocketsSockets
Sockets
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Socket Programming_theory.ppt
Socket Programming_theory.pptSocket Programming_theory.ppt
Socket Programming_theory.ppt
 
Java 1
Java 1Java 1
Java 1
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
17-Networking.pdf
17-Networking.pdf17-Networking.pdf
17-Networking.pdf
 
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
 
Understanding computer networks
Understanding computer networksUnderstanding computer networks
Understanding computer networks
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 

Plus de UC San Diego

A primer on network devices
A primer on network devicesA primer on network devices
A primer on network devicesUC San Diego
 
Datacenter traffic demand characterization
Datacenter traffic demand characterizationDatacenter traffic demand characterization
Datacenter traffic demand characterizationUC San Diego
 
Smart Homes, Buildings and Internet-of-things
Smart Homes, Buildings and Internet-of-thingsSmart Homes, Buildings and Internet-of-things
Smart Homes, Buildings and Internet-of-thingsUC San Diego
 
Social Networks analysis to characterize HIV at-risk populations - Progress a...
Social Networks analysis to characterize HIV at-risk populations - Progress a...Social Networks analysis to characterize HIV at-risk populations - Progress a...
Social Networks analysis to characterize HIV at-risk populations - Progress a...UC San Diego
 
eyeTalk - A system for helping people affected by motor neuron problems
eyeTalk - A system for helping people affected by motor neuron problemseyeTalk - A system for helping people affected by motor neuron problems
eyeTalk - A system for helping people affected by motor neuron problemsUC San Diego
 
Basic terminologies for a developer
Basic terminologies for a developerBasic terminologies for a developer
Basic terminologies for a developerUC San Diego
 
Fields in computer science
Fields in computer scienceFields in computer science
Fields in computer scienceUC San Diego
 
Network Programming with Umit project
Network Programming with Umit projectNetwork Programming with Umit project
Network Programming with Umit projectUC San Diego
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Airline reservation system db design
Airline reservation system db designAirline reservation system db design
Airline reservation system db designUC San Diego
 
Workshop on Network Security
Workshop on Network SecurityWorkshop on Network Security
Workshop on Network SecurityUC San Diego
 
Android application development
Android application developmentAndroid application development
Android application developmentUC San Diego
 
Pervasive Web Application Architecture
Pervasive Web Application ArchitecturePervasive Web Application Architecture
Pervasive Web Application ArchitectureUC San Diego
 

Plus de UC San Diego (18)

A primer on network devices
A primer on network devicesA primer on network devices
A primer on network devices
 
Datacenter traffic demand characterization
Datacenter traffic demand characterizationDatacenter traffic demand characterization
Datacenter traffic demand characterization
 
Smart Homes, Buildings and Internet-of-things
Smart Homes, Buildings and Internet-of-thingsSmart Homes, Buildings and Internet-of-things
Smart Homes, Buildings and Internet-of-things
 
Social Networks analysis to characterize HIV at-risk populations - Progress a...
Social Networks analysis to characterize HIV at-risk populations - Progress a...Social Networks analysis to characterize HIV at-risk populations - Progress a...
Social Networks analysis to characterize HIV at-risk populations - Progress a...
 
eyeTalk - A system for helping people affected by motor neuron problems
eyeTalk - A system for helping people affected by motor neuron problemseyeTalk - A system for helping people affected by motor neuron problems
eyeTalk - A system for helping people affected by motor neuron problems
 
Pirc net poster
Pirc net posterPirc net poster
Pirc net poster
 
Ajaxism
AjaxismAjaxism
Ajaxism
 
Basic terminologies for a developer
Basic terminologies for a developerBasic terminologies for a developer
Basic terminologies for a developer
 
Fields in computer science
Fields in computer scienceFields in computer science
Fields in computer science
 
FOSS Introduction
FOSS IntroductionFOSS Introduction
FOSS Introduction
 
Network Programming with Umit project
Network Programming with Umit projectNetwork Programming with Umit project
Network Programming with Umit project
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Airline reservation system db design
Airline reservation system db designAirline reservation system db design
Airline reservation system db design
 
Workshop on Network Security
Workshop on Network SecurityWorkshop on Network Security
Workshop on Network Security
 
Routing basics
Routing basicsRouting basics
Routing basics
 
Technology Quiz
Technology QuizTechnology Quiz
Technology Quiz
 
Android application development
Android application developmentAndroid application development
Android application development
 
Pervasive Web Application Architecture
Pervasive Web Application ArchitecturePervasive Web Application Architecture
Pervasive Web Application Architecture
 

Dernier

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 

Dernier (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Socket programming using java

  • 1. SOCKET PROGRAMMING IN JAVA Narendran Thangarajan, @naren_live, II Year, BE, CSE, SSN College of Engg, Chennai.
  • 2. What started it all..  Internet has emerged as a global ubiquitous media for communication  It has changed the way we live, learn, enjoy, communicate, interact, engage, etc.  To take advantage of this, businesses are ceaselessly trying to offer their services through the internet.  So a huge demand for software developers good in creating internet-enabled applications.
  • 3. Client Server Applications The Web Service is provided by the server and the clients use these services Client Server Network Client machine Server machine A client, where sockets and network This is A server, come in !!
  • 4. Sockets  Introduced in BSD 4.1 UNIX 1981.  Sockets are the endpoints of any communication over the internet.  Sockets are identified by socket addresses.  Socket Address = IP Address + Port Number
  • 5. Why IP Address + Port number? • IP Address is of the form 10.0.0.1 • Port Number can be anything from 0 to 65,535.
  • 6. Destination Socket = 10.0.0.2 : 80 IP Address – Choose network 20.0.0.0 10.0.0.0 30.0.0.0 40.0.0.0
  • 7. Destination Socket = 10.0.0.2 : 80 IP Address -> MAC Address – Locate the specific system 10.0.0.1 10.0.0.2
  • 8. Port Number – Process specific Port 10000 Port 11000 Port 120000
  • 9. Understanding Ports OutLook AVG Gmail YM Express Update Port 1 Port 2 Port 3 Port 4 Transport Layer Packet Port num data Network layer
  • 10.  Thus virtually, sockets are a connection between the two processes in different systems.  Eg : Let the socket pairs be  10.0.0.1 : 80 and 20.0.0.1 : 2000  192.168.21.10 : 3000 and 192.168.100.1 : 6000
  • 11. Networking Basics – the larger picture  Applications Layer  Standard apps  HTTP TCP STACK  FTP  Telnet Application  User apps (http,ftp,telnet,…)  Transport Layer Transport  TCP (TCP, UDP,..)  UDP Network  Network Layer (IP,..)  IP  Link Layer Link (device driver,..)  Device drivers
  • 12. Network Basics - Where are these sockets?  Applications Layer  Standard apps  HTTP TCP STACK  FTP  Telnet Application  User apps (http,ftp,telnet,…)  Programming Interface: Sockets  SOCKETS Transport  Transport Layer (TCP, UDP,..)  TCP  UDP Network (IP,..)  Network Layer Link  IP  Link Layer (device driver,..)  Device drivers
  • 13. Now into Socket programming..
  • 14. Socket Programming with TCP  Server starts first..  Server Process must be running first  Server must have created a socket which welcomes client’s connection. (Welcoming socket)  Client contacts server by..  Creating Client local TCP socket  Specify IP Address and port number of server process.  When Client socket is created, the connection is established.  When connection is established, server creates a new socket (Connection Socket) to communicate with that client and the Welcoming socket is once again waiting for connections for other clients.
  • 15. Client/Server Socket Interaction in TCP Server create socket, port=x, for incoming request: welcomeSocket = ServerSocket() Client wait for incoming TCP create socket, connection request connection setup connect to hostid, port=x connectionSocket = clientSocket = welcomeSocket.accept() Socket() send request using read request from clientSocket connectionSocket write reply to connectionSocket read reply from connectionSocket close connectionSocket close clientSocket
  • 16. Step 1 : Connection request port Server Client Step 2 : port Server port Client port Connection
  • 17. Types of Sockets in TCP  ServerSocket – the socket used by servers  Socket – Socket used by clients  Create a ServerSocket in the server and make it to wait for connections from Sockets from other clients
  • 18. The concept of Streams Client output Server input stream stream Client Server socket socket Client input Server output stream stream
  • 19. Socket Programming with UDP  No Connection between client and server.  No handshaking  The sender has to explicitly mention the IP address and the port of the destination.  The server should extract the IP Address of the datagram everytime.  Uses DatagramSocket.
  • 20. Client/server socket interaction: UDP Server Client create socket, create socket, port=x, for clientSocket = incoming request: DatagramSocket() serverSocket = DatagramSocket() Create, address (hostid, port=x), send datagram request using clientSocket read request from serverSocket write reply to serverSocket read reply from specifying client clientSocket host address, port number close clientSocket
  • 22. Conclusion  Socket Programming is very easy in Java.  Usually each and every socket is handled by a separate thread in real-time client/server environments.