SlideShare a Scribd company logo
JAVA Socket Programming

        2003.3.19
       Joonbok Lee
          KAIST
What is a socket?
• Socket
   – The combination of an IP address and a port number. (RFC 793
     ,original TCP specification)
   – The name of the Berkeley-derived application programming
     interfaces (APIs) for applications using TCP/IP protocols.
   – Two types
       • Stream socket : reliable two-way connected communication streams
       • Datagram socket


• Socket pair
   – Specified the two end points that uniquely identifies each TCP
     connection in an internet.
   – 4-tuple: (client IP address, client port number, server IP address,
     server port number)
Client-server applications
• Implementation of a protocol standard defined in an RFC. (FTP,
  HTTP, SMTP…)
    – Conform to the rules dictated by the RFC.
    – Should use the port number associated with the protocol.

• Proprietary client-server application.
    – A single developer( or team) creates both client and server
      program.
    – The developer has complete control.
    – Must be careful not to use one of the well-known port number
      defined in the RFCs.

    * well-known port number : managed by the Internet Assigned
       Numbers Authority(IANA)
Socket Programming with TCP




  Figure 2.6-1: Processes communicating through TCP
  sockets

The application developer has the ability to fix a few TCP
parameters, such as maximum buffer and maximum segment sizes.
Sockets for server and client
• Server
   – Welcoming socket
      • Welcomes some initial contact from a client.
   – Connection socket
      • Is created at initial contact of client.
      • New socket that is dedicated to the particular client.

• Client
   – Client socket
      • Initiate a TCP connection to the server by creating a socket
        object. (Three-way handshake)
      • Specify the address of the server process, namely, the IP
        address of the server and the port number of the process.
Socket functional calls
•   socket (): Create a socket
•   bind(): bind a socket to a local IP address and port #
•   listen(): passively waiting for connections
•   connect(): initiating connection to another socket
•   accept(): accept a new connection
•   Write(): write data to a socket
•   Read(): read data from a socket
•   sendto(): send a datagram to another UDP socket
•   recvfrom(): read a datagram from a UDP socket
•   close(): close a socket (tear down the connection)
Sockets




Figure 2.6-2: Client socket, welcoming socket and connection
socket
Socket-programming using TCP
TCP service: reliable byte stream transfer
                                                 socket( )
                                                 bind( )         server
                socket( )                        listen( )
  client        bind( )
                connect( )   TCP conn. request
                                                   accept( )
                 send( )     TCP ACK
                                                   recv( )

                recv( )
                                                  send( )
                close( )                          close( )

controlled by
  application     process
                                                      process
   developer      socket
                                                      socket
controlled by    TCP with
                                                     TCP with
   operating     buffers,         internet
      system                                         buffers,
                 variables
                                                     variables
Socket programming with TCP
                                                                     keyboard               monitor


Example client-server app:
•   client reads line from standard




                                                                            inFromUser
                                                             input
    input (inFromUser stream) ,                           stream

    sends to server via socket               Client
                                             Process                                       Input stream:
    (outToServer stream)                     process                                       sequence of bytes
•   server reads line from socket     output stream:                                       into process
•   server converts line to           sequence of bytes
    uppercase, sends back to client   out of process




                                                                                                inFromServer
                                                                            outToServer
•   client reads, prints modified                      output
                                                      stream
                                                                                                                  input
                                                                                                               stream

    line from socket
    (inFromServer stream)                                                client TCP
                                                                            clientSocket
                                                                            socket                                          TCP
                                                                                                                          socket

                                                                     to network           from network
Client/server socket interaction: TCP
Server (running on hostid)                     Client
     create socket,
     port=x, for
     incoming request:
     welcomeSocket =
        ServerSocket()

                            TCP              create socket,
     wait for incoming
     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
                                                clientSocket
     close
     connectionSocket                           close
                                                clientSocket
JAVA TCP Sockets
•   In Package java.net
    – java.net.Socket
        • Implements client sockets (also called just “sockets”).
        • An endpoint for communication between two machines.
        • Constructor and Methods
              – Socket(String host, int port): Creates a stream socket and connects it to the
                specified port number on the named host.
              – InputStream getInputStream()
              – OutputStream getOutputStream()
              – close()

    – java.net.ServerSocket
        •   Implements server sockets.
        •   Waits for requests to come in over the network.
        •   Performs some operation based on the request.
        •   Constructor and Methods
              – ServerSocket(int port)
              – Socket Accept(): Listens for a connection to be made to this socket and
                accepts it. This method blocks until a connection is made.
TCPClient.java
import java.io.*;
import java.net.*;

class TCPClient {
   public static void main(String argv[]) throws Exception
   {
           String sentence;
           String modifiedSentence;

          BufferedReader inFromUser =
             new BufferedReader(new InputStreamReader(System.in));

          Socket clientSocket = new Socket("hostname", 6789);
       
            DataOutputStream outToServer =
             new DataOutputStream(clientSocket.getOutputStream());
TCPClient.java
             BufferedReader inFromServer =
               new BufferedReader(new
     InputStreamReader(clientSocket.getInputStream()));
       
     sentence = inFromUser.readLine();
       
     outToServer.writeBytes(sentence + 'n');
       
     modifiedSentence = inFromServer.readLine();
       
     System.out.println("FROM SERVER: " + modifiedSentence);
      
     clientSocket.close();
                       
     }
}
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
  public static void main(String argv[]) throws Exception
       {
         String clientSentence;
         String capitalizedSentence;
 
         ServerSocket welcomeSocket = new
   ServerSocket(6789);
    
         while(true) {

             Socket connectionSocket = welcomeSocket.accept();
          
             BufferedReader inFromClient = new BufferedReader(new
                 InputStreamReader(connectionSocket.getInputStream()));
TCPServer.java

           DataOutputStream  outToClient =
                  new DataOutputStream(connectionSocket.getOutputStream());
          
             clientSentence = inFromClient.readLine();
          
             capitalizedSentence = clientSentence.toUpperCase() + 'n';

              outToClient.writeBytes(capitalizedSentence);
           
       }
    }
}
Socket Programming with
                UDP
• UDP
   –   Connectionless and unreliable service.
   –   There isn’t an initial handshaking phase.
   –   Doesn’t have a pipe.
   –   transmitted data may be received out of order, or lost



• Socket Programming with UDP
   – No need for a welcoming socket.
   – No streams are attached to the sockets.
   – the sending hosts creates “packets” by attaching the IP destination
     address and port number to each batch of bytes.
   – The receiving process must unravel to received packet to obtain the
     packet’s information bytes.
Client/server socket interaction: UDP
Server (running on hostid)   Client

     create socket,
     port=x, for             create socket,
                             clientSocket =
     incoming request:       DatagramSocket()
     serverSocket =
     DatagramSocket()
                             Create, address (hostid, port=x,
                             send datagram request
                             using clientSocket
      read request from
      serverSocket

      write reply to
      serverSocket
      specifying client        read reply from
      host address,            clientSocket
      port umber               close
                               clientSocket
Example: Java client (UDP)
                                     keyboard               monitor




                                             inFromUser
                             input
                          stream


            Client
            Process
                                                                                                   Input: receives
             process
                                                                                                   packet (TCP
                                                                                                   received “byte
 Output: sends
                                                                                                   stream”)
 packet (TCP sent



                                                                 receivePacket
                                             sendPacket
 “byte stream”)          UDP                                                       UDP
                       packet                                                    packet



                                          client UDP
                                            clientSocket
                                             socket                                         UDP
                                                                                          socket

                                     to network           from network
JAVA UDP Sockets
• In Package java.net
  – java.net.DatagramSocket
    • A socket for sending and receiving datagram
      packets.
    • Constructor and Methods
       – DatagramSocket(int port): Constructs a datagram
         socket and binds it to the specified port on the local
         host machine.
       – void receive( DatagramPacket p)
       – void send( DatagramPacket p)
       – void close()
UDPClient.java
import java.io.*;
import java.net.*;
    
   class UDPClient {
       public static void main(String args[]) throws Exception
       {
    
         BufferedReader inFromUser =
           new BufferedReader(new InputStreamReader(System.in));
    
         DatagramSocket clientSocket = new
   DatagramSocket();
    
         InetAddress IPAddress =
   InetAddress.getByName("hostname");
    
         byte[] sendData = new byte[1024];
         byte[] receiveData = new byte[1024];
    
         String sentence = inFromUser.readLine();
    
         sendData = sentence.getBytes();
UDPClient.java
      DatagramPacket sendPacket =
              new DatagramPacket(sendData, sendData.length,
     IPAddress, 9876);
      
      clientSocket.send(sendPacket);
      
      DatagramPacket receivePacket =
              new DatagramPacket(receiveData, receiveData.length);
      
      clientSocket.receive(receivePacket);
      
      String modifiedSentence =
              new String(receivePacket.getData());
      
      System.out.println("FROM SERVER:" + modifiedSentence);
     
      clientSocket.close();
      
         }
     }
UDPServer.java
import java.io.*;
import java.net.*;
    
class UDPServer {
     public static void main(String args[]) throws Exception
       {
    
         DatagramSocket serverSocket = new
   DatagramSocket(9876);
    
         byte[] receiveData = new byte[1024];
         byte[] sendData  = new byte[1024];
    
         while(true)
           {
    
             DatagramPacket receivePacket =
                new DatagramPacket(receiveData, receiveData.length);
    
             serverSocket.receive(receivePacket);
    
             String sentence = new String(receivePacket.getData());
UDPServer.java
 
        InetAddress IPAddress = receivePacket.getAddress();
      
        int port = receivePacket.getPort();
      
       String capitalizedSentence = sentence.toUpperCase();
        sendData = capitalizedSentence.getBytes();
      
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, port);
      
         serverSocket.send(sendPacket);

      }
   }
}
Building a Simple Web Server
• Handles only one HTTP request
• Accepts and parses the HTTP request
• Gets the required file from the server’s
  file system.
• Creates an HTTP response message
  consisting of the requested file
  preceded by header lines
• Sends the response directly to the client
WebServer.java
import java.io.*;
import java.net.*;
import java.util.*;
class WebServer{
    public static void main(String argv[]) throws Exception  {
          String requestMessageLine;
          String fileName;
          ServerSocket listenSocket = new ServerSocket(6789);
          Socket connectionSocket = listenSocket.accept();

          BufferedReader inFromClient =
                 new BufferedReader(new
                      InputStreamReader(connectionSocket.getInputStream()));

          DataOutputStream outToClient =
              new DataOutputStream(connectionSocket.getOutputStream());
       
WebServer.java
requestMessageLine = inFromClient.readLine();
         
StringTokenizer tokenizedLine =
     new StringTokenizer(requestMessageLine);
     
if (tokenizedLine.nextToken().equals("GET")){
          fileName = tokenizedLine.nextToken();
          if (fileName.startsWith("/") == true )
                   fileName  = fileName.substring(1);
          
          File file = new File(fileName);
           int numOfBytes = (int) file.length();
          FileInputStream inFile  = new FileInputStream (fileName);
           byte[] fileInBytes = new byte[numOfBytes];
           
          inFile.read(fileInBytes);
WebServer.java
     outToClient.writeBytes("HTTP/1.0 200 Document Followsrn");
     
     if (fileName.endsWith(".jpg"))
          outToClient.writeBytes("Content-Type: image/jpegrn");
              
     if (fileName.endsWith(".gif"))
          outToClient.writeBytes("Content-Type: image/gifrn");
         
     outToClient.writeBytes("Content-Length: " + numOfBytes + "rn");
             
     outToClient.writeBytes("rn");
     outToClient.write(fileInBytes, 0, numOfBytes);
     connectionSocket.close();
   }
    else System.out.println("Bad Request Message");
  }
}
Concurrent server
• Servers need to handle a new
  connection request while processing
  previous requests.
  – Most TCP servers are designed to be
    concurrent.
• When a new connection request arrives
  at a server, the server accepts and
  invokes a new process to handle the
  new client.
How to handle the port numbers
cosmos% netstat –a –n –f inet
Active Internet connections (including servers)
Proto      Recv-Q Send-Q Local Address            Foreign Address      (state)
tcp        0        0          *.23               *.*                  LISTEN

cosmos% netstat –a –n –f inet
Proto   Recv-Q Send-Q Local Address               Foreign Address      (state)
tcp     0         0           192.249.24.2.23     192.249.24.31.1029   ESTABLISHED
tcp     0         0           *.23                *.*                  LISTEN

cosmos% netstat –a –n –f inet
Proto   Recv-Q Send-Q Local Address               Foreign Address      (state)
tcp     0         0           192.249.24.2.23     192.249.24.31.1029   ESTABLISHED
tcp     0         0           192.249.24.2.23     192.249.24.31.1030   ESTABLISHED
tcp     0         0           *.23                *.*                  LISTEN
Socket programming: references

C-language tutorial (audio/slides):
• “Unix Network Programming” (J. Kurose),
http://manic.cs.umass.edu/~amldemo/courseware/intro.html

Java-tutorials:
• “All About Sockets” (Sun tutorial),
  http://www.javaworld.com/javaworld/jw-12-1996/jw-12-
  sockets.html
• “Socket Programming in Java: a tutorial,”
  http://www.javaworld.com/javaworld/jw-12-1996/jw-12-
  sockets.html

More Related Content

PDF
Socket programming using java
UC San Diego
 
PPTX
Socket programming in Java (PPTX)
UC San Diego
 
PPTX
Data Encryption Standard (DES)
Haris Ahmed
 
PPTX
Handover in Mobile Computing
KABILESH RAMAR
 
PPTX
IPV4 vs IPV6
Devang Doshi
 
PPT
Application layer protocols
JUW Jinnah University for Women
 
PPT
Networking and Internetworking Devices
21viveksingh
 
PPTX
IEEE 802.11 Architecture and Services
Dhrumil Panchal
 
Socket programming using java
UC San Diego
 
Socket programming in Java (PPTX)
UC San Diego
 
Data Encryption Standard (DES)
Haris Ahmed
 
Handover in Mobile Computing
KABILESH RAMAR
 
IPV4 vs IPV6
Devang Doshi
 
Application layer protocols
JUW Jinnah University for Women
 
Networking and Internetworking Devices
21viveksingh
 
IEEE 802.11 Architecture and Services
Dhrumil Panchal
 

What's hot (20)

PPTX
Link state routing protocol
Aung Thu Rha Hein
 
PPTX
Leaky bucket A
Syed Shaheer Gilani
 
PPTX
Operating System Security
Ramesh Upadhaya
 
PPTX
Unicasting , Broadcasting And Multicasting New
techbed
 
PPT
Topic: Virtual circuit & message switching
Dr Rajiv Srivastava
 
PPTX
Network Layer
Dr Shashikant Athawale
 
PPTX
Feistel cipher
MDKAWSARAHMEDSAGAR
 
PPTX
The Art of Debugging.pptx
KarthigaiSelviS3
 
PPTX
Software process
Jennifer Polack
 
PPTX
Introduction to java
Veerabadra Badra
 
PDF
Sun RPC (Remote Procedure Call)
Peter R. Egli
 
PPT
Java oops PPT
kishu0005
 
PPT
Secure Socket Layer
Naveen Kumar
 
PPTX
Modules in Python Programming
sambitmandal
 
PPT
Transport services
Navin Kumar
 
PDF
DNS (Domain Name System)
Shashidhara Vyakaranal
 
PPTX
Inheritance in java
Tech_MX
 
PPTX
GO BACK N PROTOCOL
shayan singla
 
PPTX
WLAN
vivek patel
 
PPT
DES (Data Encryption Standard) pressentation
sarhadisoftengg
 
Link state routing protocol
Aung Thu Rha Hein
 
Leaky bucket A
Syed Shaheer Gilani
 
Operating System Security
Ramesh Upadhaya
 
Unicasting , Broadcasting And Multicasting New
techbed
 
Topic: Virtual circuit & message switching
Dr Rajiv Srivastava
 
Network Layer
Dr Shashikant Athawale
 
Feistel cipher
MDKAWSARAHMEDSAGAR
 
The Art of Debugging.pptx
KarthigaiSelviS3
 
Software process
Jennifer Polack
 
Introduction to java
Veerabadra Badra
 
Sun RPC (Remote Procedure Call)
Peter R. Egli
 
Java oops PPT
kishu0005
 
Secure Socket Layer
Naveen Kumar
 
Modules in Python Programming
sambitmandal
 
Transport services
Navin Kumar
 
DNS (Domain Name System)
Shashidhara Vyakaranal
 
Inheritance in java
Tech_MX
 
GO BACK N PROTOCOL
shayan singla
 
DES (Data Encryption Standard) pressentation
sarhadisoftengg
 
Ad

Viewers also liked (17)

PPT
Networking Java Socket Programming
Mousmi Pawar
 
PPTX
prosthetics
Shruti Patil
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
Routing Protocols and Concepts - Chapter 1
CAVC
 
PPT
14 file handling
APU
 
PPTX
basics of file handling
pinkpreet_kaur
 
PPSX
Congestion control in TCP
selvakumar_b1985
 
PPT
Socket System Calls
Avinash Varma Kalidindi
 
PPT
TCP congestion control
Shubham Jain
 
PPT
A Short Java Socket Tutorial
Guo Albert
 
PPT
Network programming in Java
Tushar B Kute
 
PPT
Socket programming-tutorial-sk
sureshkarthick37
 
PPT
Socket Programming Tutorial
Jignesh Patel
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PPT
Amputaciones de miembro_inferior
Osvaldo Toscano ILTEC
 
PPTX
Network programming in java - PPT
kamal kotecha
 
PPT
PROTESIS - Tipos y Caracteristicas
Marcial Lezama Stgo
 
Networking Java Socket Programming
Mousmi Pawar
 
prosthetics
Shruti Patil
 
Java Input Output and File Handling
Sunil OS
 
Routing Protocols and Concepts - Chapter 1
CAVC
 
14 file handling
APU
 
basics of file handling
pinkpreet_kaur
 
Congestion control in TCP
selvakumar_b1985
 
Socket System Calls
Avinash Varma Kalidindi
 
TCP congestion control
Shubham Jain
 
A Short Java Socket Tutorial
Guo Albert
 
Network programming in Java
Tushar B Kute
 
Socket programming-tutorial-sk
sureshkarthick37
 
Socket Programming Tutorial
Jignesh Patel
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Amputaciones de miembro_inferior
Osvaldo Toscano ILTEC
 
Network programming in java - PPT
kamal kotecha
 
PROTESIS - Tipos y Caracteristicas
Marcial Lezama Stgo
 
Ad

Similar to Socket programming (20)

PDF
JavaSockets-Session10 New York university.pdf
jose19881
 
PPTX
Networking in Python2025 (programs allll)
PriyankaPatil919748
 
PPTX
Basics of Socket Programming using python
NalinadeviKadiresan1
 
PDF
Socket Programming
elliando dias
 
PPTX
Socket & Server Socket
Hemant Chetwani
 
PPT
Socket programming in C
Deepak Swain
 
PPT
Network programming in Java
Tushar B Kute
 
PPTX
Java 1
VidyaVarshini3
 
PDF
17-Networking.pdf
sophia763824
 
PPT
java networking
Waheed Warraich
 
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
PPT
Socket Programming_theory.ppt
mdrobinhossain4
 
PPT
Sockets
sivindia
 
PPT
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 
PPTX
Java - Sockets
Riccardo Cardin
 
PPT
Socket Programming in Java.ppt yeh haii
inambscs4508
 
PPT
Unit 8 Java
arnold 7490
 
DOC
socket programming
prashantzagade
 
DOC
socket programming
prashantzagade
 
DOC
T2
Mo Ch
 
JavaSockets-Session10 New York university.pdf
jose19881
 
Networking in Python2025 (programs allll)
PriyankaPatil919748
 
Basics of Socket Programming using python
NalinadeviKadiresan1
 
Socket Programming
elliando dias
 
Socket & Server Socket
Hemant Chetwani
 
Socket programming in C
Deepak Swain
 
Network programming in Java
Tushar B Kute
 
17-Networking.pdf
sophia763824
 
java networking
Waheed Warraich
 
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
Socket Programming_theory.ppt
mdrobinhossain4
 
Sockets
sivindia
 
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
 
Java - Sockets
Riccardo Cardin
 
Socket Programming in Java.ppt yeh haii
inambscs4508
 
Unit 8 Java
arnold 7490
 
socket programming
prashantzagade
 
socket programming
prashantzagade
 
T2
Mo Ch
 

Recently uploaded (20)

PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
High Ground Student Revision Booklet Preview
jpinnuck
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
High Ground Student Revision Booklet Preview
jpinnuck
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 

Socket programming

  • 1. JAVA Socket Programming 2003.3.19 Joonbok Lee KAIST
  • 2. What is a socket? • Socket – The combination of an IP address and a port number. (RFC 793 ,original TCP specification) – The name of the Berkeley-derived application programming interfaces (APIs) for applications using TCP/IP protocols. – Two types • Stream socket : reliable two-way connected communication streams • Datagram socket • Socket pair – Specified the two end points that uniquely identifies each TCP connection in an internet. – 4-tuple: (client IP address, client port number, server IP address, server port number)
  • 3. Client-server applications • Implementation of a protocol standard defined in an RFC. (FTP, HTTP, SMTP…) – Conform to the rules dictated by the RFC. – Should use the port number associated with the protocol. • Proprietary client-server application. – A single developer( or team) creates both client and server program. – The developer has complete control. – Must be careful not to use one of the well-known port number defined in the RFCs. * well-known port number : managed by the Internet Assigned Numbers Authority(IANA)
  • 4. Socket Programming with TCP Figure 2.6-1: Processes communicating through TCP sockets The application developer has the ability to fix a few TCP parameters, such as maximum buffer and maximum segment sizes.
  • 5. Sockets for server and client • Server – Welcoming socket • Welcomes some initial contact from a client. – Connection socket • Is created at initial contact of client. • New socket that is dedicated to the particular client. • Client – Client socket • Initiate a TCP connection to the server by creating a socket object. (Three-way handshake) • Specify the address of the server process, namely, the IP address of the server and the port number of the process.
  • 6. Socket functional calls • socket (): Create a socket • bind(): bind a socket to a local IP address and port # • listen(): passively waiting for connections • connect(): initiating connection to another socket • accept(): accept a new connection • Write(): write data to a socket • Read(): read data from a socket • sendto(): send a datagram to another UDP socket • recvfrom(): read a datagram from a UDP socket • close(): close a socket (tear down the connection)
  • 7. Sockets Figure 2.6-2: Client socket, welcoming socket and connection socket
  • 8. Socket-programming using TCP TCP service: reliable byte stream transfer socket( ) bind( ) server socket( ) listen( ) client bind( ) connect( ) TCP conn. request accept( ) send( ) TCP ACK recv( ) recv( ) send( ) close( ) close( ) controlled by application process process developer socket socket controlled by TCP with TCP with operating buffers, internet system buffers, variables variables
  • 9. Socket programming with TCP keyboard monitor Example client-server app: • client reads line from standard inFromUser input input (inFromUser stream) , stream sends to server via socket Client Process Input stream: (outToServer stream) process sequence of bytes • server reads line from socket output stream: into process • server converts line to sequence of bytes uppercase, sends back to client out of process inFromServer outToServer • client reads, prints modified output stream input stream line from socket (inFromServer stream) client TCP clientSocket socket TCP socket to network from network
  • 10. Client/server socket interaction: TCP Server (running on hostid) Client create socket, port=x, for incoming request: welcomeSocket = ServerSocket() TCP create socket, wait for incoming 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 clientSocket close connectionSocket close clientSocket
  • 11. JAVA TCP Sockets • In Package java.net – java.net.Socket • Implements client sockets (also called just “sockets”). • An endpoint for communication between two machines. • Constructor and Methods – Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host. – InputStream getInputStream() – OutputStream getOutputStream() – close() – java.net.ServerSocket • Implements server sockets. • Waits for requests to come in over the network. • Performs some operation based on the request. • Constructor and Methods – ServerSocket(int port) – Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made.
  • 12. TCPClient.java import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception {         String sentence;         String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789);         DataOutputStream outToServer =          new DataOutputStream(clientSocket.getOutputStream());
  • 13. TCPClient.java BufferedReader inFromServer =           new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));         sentence = inFromUser.readLine();         outToServer.writeBytes(sentence + 'n');         modifiedSentence = inFromServer.readLine();         System.out.println("FROM SERVER: " + modifiedSentence);        clientSocket.close();                    } }
  • 14. TCPServer.java import java.io.*; import java.net.*; class TCPServer {   public static void main(String argv[]) throws Exception     {       String clientSentence;       String capitalizedSentence;   ServerSocket welcomeSocket = new ServerSocket(6789);   while(true) { Socket connectionSocket = welcomeSocket.accept();            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
  • 15. TCPServer.java            DataOutputStream  outToClient =              new DataOutputStream(connectionSocket.getOutputStream());            clientSentence = inFromClient.readLine();            capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence);         } } }
  • 16. Socket Programming with UDP • UDP – Connectionless and unreliable service. – There isn’t an initial handshaking phase. – Doesn’t have a pipe. – transmitted data may be received out of order, or lost • Socket Programming with UDP – No need for a welcoming socket. – No streams are attached to the sockets. – the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes. – The receiving process must unravel to received packet to obtain the packet’s information bytes.
  • 17. Client/server socket interaction: UDP Server (running on hostid) Client create socket, port=x, for create socket, clientSocket = incoming request: DatagramSocket() serverSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read request from serverSocket write reply to serverSocket specifying client read reply from host address, clientSocket port umber close clientSocket
  • 18. Example: Java client (UDP) keyboard monitor inFromUser input stream Client Process Input: receives process packet (TCP received “byte Output: sends stream”) packet (TCP sent receivePacket sendPacket “byte stream”) UDP UDP packet packet client UDP clientSocket socket UDP socket to network from network
  • 19. JAVA UDP Sockets • In Package java.net – java.net.DatagramSocket • A socket for sending and receiving datagram packets. • Constructor and Methods – DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. – void receive( DatagramPacket p) – void send( DatagramPacket p) – void close()
  • 20. UDPClient.java import java.io.*; import java.net.*;   class UDPClient {     public static void main(String args[]) throws Exception     {         BufferedReader inFromUser =         new BufferedReader(new InputStreamReader(System.in));         DatagramSocket clientSocket = new DatagramSocket();         InetAddress IPAddress = InetAddress.getByName("hostname");         byte[] sendData = new byte[1024];       byte[] receiveData = new byte[1024];         String sentence = inFromUser.readLine();         sendData = sentence.getBytes();
  • 21. UDPClient.java       DatagramPacket sendPacket =          new DatagramPacket(sendData, sendData.length, IPAddress, 9876);    clientSocket.send(sendPacket);    DatagramPacket receivePacket =          new DatagramPacket(receiveData, receiveData.length);    clientSocket.receive(receivePacket);    String modifiedSentence =          new String(receivePacket.getData());    System.out.println("FROM SERVER:" + modifiedSentence);       clientSocket.close();       } }
  • 22. UDPServer.java import java.io.*; import java.net.*;   class UDPServer {   public static void main(String args[]) throws Exception     {         DatagramSocket serverSocket = new DatagramSocket(9876);         byte[] receiveData = new byte[1024];       byte[] sendData  = new byte[1024];         while(true)         {             DatagramPacket receivePacket =              new DatagramPacket(receiveData, receiveData.length);             serverSocket.receive(receivePacket);             String sentence = new String(receivePacket.getData());
  • 23. UDPServer.java      InetAddress IPAddress = receivePacket.getAddress();      int port = receivePacket.getPort();     String capitalizedSentence = sentence.toUpperCase();         sendData = capitalizedSentence.getBytes();      DatagramPacket sendPacket =        new DatagramPacket(sendData, sendData.length, IPAddress, port);       serverSocket.send(sendPacket);       } } }
  • 24. Building a Simple Web Server • Handles only one HTTP request • Accepts and parses the HTTP request • Gets the required file from the server’s file system. • Creates an HTTP response message consisting of the requested file preceded by header lines • Sends the response directly to the client
  • 25. WebServer.java import java.io.*; import java.net.*; import java.util.*; class WebServer{     public static void main(String argv[]) throws Exception  {           String requestMessageLine;      String fileName;           ServerSocket listenSocket = new ServerSocket(6789);      Socket connectionSocket = listenSocket.accept();           BufferedReader inFromClient =             new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());        
  • 26. WebServer.java requestMessageLine = inFromClient.readLine();           StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);       if (tokenizedLine.nextToken().equals("GET")){           fileName = tokenizedLine.nextToken();           if (fileName.startsWith("/") == true )               fileName  = fileName.substring(1);            File file = new File(fileName);       int numOfBytes = (int) file.length();           FileInputStream inFile  = new FileInputStream (fileName);            byte[] fileInBytes = new byte[numOfBytes];        inFile.read(fileInBytes);
  • 27. WebServer.java      outToClient.writeBytes("HTTP/1.0 200 Document Followsrn");       if (fileName.endsWith(".jpg"))      outToClient.writeBytes("Content-Type: image/jpegrn");           if (fileName.endsWith(".gif"))      outToClient.writeBytes("Content-Type: image/gifrn");           outToClient.writeBytes("Content-Length: " + numOfBytes + "rn");          outToClient.writeBytes("rn"); outToClient.write(fileInBytes, 0, numOfBytes);      connectionSocket.close(); }     else System.out.println("Bad Request Message"); } }
  • 28. Concurrent server • Servers need to handle a new connection request while processing previous requests. – Most TCP servers are designed to be concurrent. • When a new connection request arrives at a server, the server accepts and invokes a new process to handle the new client.
  • 29. How to handle the port numbers cosmos% netstat –a –n –f inet Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 *.23 *.* LISTEN cosmos% netstat –a –n –f inet Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 192.249.24.2.23 192.249.24.31.1029 ESTABLISHED tcp 0 0 *.23 *.* LISTEN cosmos% netstat –a –n –f inet Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 192.249.24.2.23 192.249.24.31.1029 ESTABLISHED tcp 0 0 192.249.24.2.23 192.249.24.31.1030 ESTABLISHED tcp 0 0 *.23 *.* LISTEN
  • 30. Socket programming: references C-language tutorial (audio/slides): • “Unix Network Programming” (J. Kurose), http://manic.cs.umass.edu/~amldemo/courseware/intro.html Java-tutorials: • “All About Sockets” (Sun tutorial), http://www.javaworld.com/javaworld/jw-12-1996/jw-12- sockets.html • “Socket Programming in Java: a tutorial,” http://www.javaworld.com/javaworld/jw-12-1996/jw-12- sockets.html

Editor's Notes

  • #3: TLI ( Transport Layer Interface )