[go: up one dir, main page]

0% found this document useful (0 votes)
31 views45 pages

Lecture 3: Introduction To Socket Programming

The document discusses sockets and socket programming. It defines a socket as an interface between an application and the network that allows an application to send and receive data through the network. It describes two main types of sockets: TCP sockets which provide reliable, in-order delivery, and UDP sockets which provide unreliable delivery with no guarantees of order. It also discusses how sockets are used in common applications like file transfer and streaming media.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views45 pages

Lecture 3: Introduction To Socket Programming

The document discusses sockets and socket programming. It defines a socket as an interface between an application and the network that allows an application to send and receive data through the network. It describes two main types of sockets: TCP sockets which provide reliable, in-order delivery, and UDP sockets which provide unreliable delivery with no guarantees of order. It also discusses how sockets are used in common applications like file transfer and streaming media.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Lecture 3 : Introduction to Socket Programming

1
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
What is a socket?
• Port vs. Socket

• An interface between application and network


• The application creates a socket
• The socket type dictates the style of communication
• reliable vs. best effort
• connection-oriented vs. connectionless

• Once configured the application can


• pass data to the socket for network transmission
• receive data from the socket (transmitted through the
network by some other host)

2
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
TCP/IP Stack

3
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Two essential types of sockets
• TCP Socket • UDP Socket
• reliable delivery • unreliable delivery
• in-order guaranteed • no order guarantees
• connection-oriented • no notion of “connection” – app
• bidirectional indicates dest. for each packet
• can send or receive

App

App D1
3 2
1
socket Dest.
3 2 1
socket D2

D3
4
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Applications

• TCP (Transmission control protocol)


- Point to point chat applications, File transfer
(FTP), Email (SMTP)
- Used when there’s a requirement for guaranteed
delivery

• UDP (User datagram protocol)


– Streaming, Multicast/Broadcast
- Useful when the speed of more important than
the assurance of delivery
5
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
A Socket-eye view of the Internet

medellin.cs.columbia.edu
(128.59.21.14)

newworld.cs.umass.edu
(128.119.245.93)

cluster.cs.columbia.edu
(128.59.21.14, 128.59.16.7,
128.59.16.5, 128.59.16.4)

• Each host machine has an IP address


• When a packet arrives at a host

6
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Ports
• Each host has 65,536 ports
Port 0
• Some ports are reserved
for specific apps Port 1
• 20,21: FTP
• 23: Telnet Port 65535
• 80: HTTP
• see RFC 1700 (about 2000 A socket provides an interface
ports are reserved) to send data to/from the
network through a port

7
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Addresses, Ports and Sockets

• In TCP, only one application (process) can listen to a


port
• In UDP Multiple applications (processes) may listen to
incoming messages on a single port
• Like apartments and mailboxes
• You are the application
• Your apartment building address is the address
• Your mailbox is the port
• The post-office is the network
• Each family (process) of the apartment complex (computer)
communicates with some same mailbox (port)
8
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
TCP Sockets

Client socket, welcoming socket (passive) and connection socket (active)

9
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Connection setup
• Passive participant • Active participant
• step 1: listen (for incoming
requests)
• step 2: request & establish
• step 3: accept (a request)
connection
• step 4: data transfer
• The accepted connection is
• step 4: data transfer
on a new socket
Passive Participant
• The old socket continues to
listen for other active a-sock-1 l-sock a-sock-2
participants

socket socket
Active 1 Active 2
10
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Dealing with blocking

• Calls to sockets can be blocking (no other client may be


able to connect to the server)
• Can be resolved using multi-threaded programming
• Start a new thread for every incoming connection

11
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Java Sockets Programming

• The package java.net provides support for sockets


programming (and more).

• Typically you import everything defined in this package


with:

import java.net.*;

12
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Classes

InetAddress

Socket

ServerSocket

DatagramSocket

DatagramPacket

13
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
InetAddress class
• Static methods you can use to create new InetAddress
objects.
• getByName(String host)
• getAllByName(String host)
• getLocalHost()

InetAddress x = InetAddress.getByName(
“cse.unr.edu”);
Throws UnknownHostException

14
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
try {

InetAddress a = InetAddress.getByName(hostname);

System.out.println(hostname + ":" +
a.getHostAddress());

} catch (UnknownHostException e) {

System.out.println("No address found for " +


hostname);

SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna


Socket class
• Corresponds to active TCP sockets only!
• client sockets
• socket returned by accept();

• Passive sockets are supported by a different class:


• ServerSocket

• UDP sockets are supported by


• DatagramSocket

16
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
JAVA TCP Sockets
• java.net.Socket
• Implements client sockets (also called just “sockets”).
• An endpoint for communication between two
machines.
• Uses input/output streams to pass messages

• java.net.ServerSocket
• Implements server sockets.
• Waits for requests to come in over the network.
• Accepts the client connection requests
• Performs some operation based on each request

17
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Socket Constructors
• Constructor creates a TCP connection to a named TCP server.
• There are a number of constructors:

Socket(InetAddress server, int port);

Socket(InetAddress server, int port,


InetAddress local, int localport);

Socket(String hostname, int port);

18
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Socket Methods
void close();
InetAddress getInetAddress();
InetAddress getLocalAddress();
InputStream getInputStream();
OutputStream getOutputStream();

• Lots more (setting/getting socket options, partial close, etc.)

19
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Socket I/O
• Socket I/O is based on the Java I/O support
• in the package java.io

• InputStream and OutputStream are abstract classes


• common operations defined for all kinds of InputStreams,
OutputStreams…

20
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
InputStream Basics

// reads some number of bytes and


// puts in buffer array b
int read(byte[] b);

// reads up to len bytes


int read(byte[] b, int off, int len);

Both methods can throw IOException.


Both return –1 on EOF.

21
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
OutputStream Basics

// writes b.length bytes


void write(byte[] b);

// writes len bytes starting


// at offset off
void write(byte[] b, int off, int len);

Both methods can throw IOException.

22
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
ServerSocket Class
(TCP Passive Socket)
• Constructors:

ServerSocket(int port);

ServerSocket(int port, int backlog);

ServerSocket(int port, int backlog,


InetAddress bindAddr);

23
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
ServerSocket Methods
Socket accept();

void close();

InetAddress getInetAddress();

int getLocalPort();

throw IOException, SecurityException

24
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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


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

inFromServer
outToServer
output input
from socket (inFromServer stream stream

stream)
client TCP
clientSocket
socket TCP
socket

to network from network

25
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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
26
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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());

SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna


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();
                  
}
}
28
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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()));

SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna


TCPServer.java

           DataOutputStream  outToClient =


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

outToClient.writeBytes(capitalizedSentence);
       
}
}
}

30
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
UDP Sockets
• DatagramSocket class

• DatagramPacket class needed to specify the payload


• incoming or outgoing

31
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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.

32
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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()

33
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
DatagramSocket Constructors
DatagramSocket();

DatagramSocket(int port);

DatagramSocket(int port, InetAddress a);

All can throw SocketException or SecurityException

34
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Datagram Methods

void connect(InetAddress, int port);

void close();

void receive(DatagramPacket p);

void send(DatagramPacket p);

Lots more!

35
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Datagram Packet

• Contain the payload


• a byte array

• Can also be used to specify the destination address


• when not using connected mode UDP

36
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
DatagramPacket Constructors

For receiving:

DatagramPacket( byte[] buf, int len);

For sending:

DatagramPacket( byte[] buf, int len


InetAddress a, int port);

37
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
DatagramPacket methods

byte[] getData();
void setData(byte[] buf);

void setAddress(InetAddress a);


void setPort(int port);

InetAddress getAddress();
int getPort();

38
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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

39
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Client/server socket interaction: UDP
Server (running on hostid) 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
specifying client read reply from
host address, clientSocket
port umber close
clientSocket

40
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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();
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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();
 
    }
}
42
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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());
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
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);

      }
}
}

44
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna
Summary
• Socket programming is the most fundamental form
of Client-Server distributed computing available for
app. developers
• Can be used to develop client-server distributed
applications (e.g. Messaging applications)
• However, most real-world distributed systems use
more high level distributed computing technologies
(E.g. Web services, EJBs)
• Yet the underlying communication mechanism of
these high level Dist. Computing frameworks is
socket communication

45
SE3020 | Distributed Systems | Socket Programming | Dharshana Kasthurirathna

You might also like