Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Week 5 Socket Programming

Uploaded by

Binay Adhikari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 5 Socket Programming

Uploaded by

Binay Adhikari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Distributed Computer Systems

CT024-3-3-DCOMS and Version VC1

Socket Programming
Topic & Structure of The
Lesson
• Real world socket
• Socket with UDP
• Socket with TCP
• Socket reference

CT024-3-3 Distributed Computer Systems Socket Programming 2 of 55


Learning Outcomes

• At the end of this topic, You


should be able to
• Understand the concept of Socket
• Difference between TCP and UDP Socket
• Explaining about the Socket Reference

CT024-3-3 Distributed Computer Systems Socket Programming 3 of 55


Key Terms You Must Be
Able To Use
• If you have mastered this topic, you should be able
to use the following terms correctly in your
assignments and exams:
- Socket
- TCP
- UDP
- Socket Reference

CT024-3-3 Distributed Computer Systems Socket Programming 4 of 55


Real World Sockets

CT024-3-3 Distributed Computer Systems Socket Programming 5 of 55


Socket programming
Goal: learn how to build client/server applications
that communicate using sockets

Socket API asocket


host-local,
• introduced in BSD4.1 UNIX, application-created/own
1981 ed,
• explicitly created, used, OS-controlled interface
released by apps (a “door”) into which
• client/server paradigm application process can
both send and
• two types of transport service
receive messages
via socket API: to/from another (remote
– unreliable datagram or
– reliable, byte stream- local) application
oriented process

CT024-3-3 Distributed Computer Systems Socket Programming 6 of 55


Socket-programming using TCP
Socket: a door between application process and end-
end-transport protocol (UDP or TCP)
TCP service: reliable transfer of bytes from one process
to another

controlled by
controlled by process application
application process
developer
developer socket socket
controlled by TCP with TCP with controlled by
buffers, operating
operating buffers, internet system
system variables variables

host or host or
server server

CT024-3-3 Distributed Computer Systems Socket Programming 7 of 55


Socket programming with TCP
Client must contact server • When client creates socket:
• server process must first be client TCP establishes
running connection to server TCP
• server must have created • When contacted by client,
socket (door) that welcomes server TCP creates new
client’s contact socket for server process to
communicate with client
Client contacts server by:
– allows server to talk with
• creating client-local TCP
multiple clients
socket
• specifying IP address, port
application viewpoint
number of server process
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server

CT024-3-3 Distributed Computer Systems Socket Programming 8 of 55


Socket programming with TCP
Example client-server app: Input stream: sequence of
• client reads line from standard bytes into process
input (inFromUser stream) , Output stream: sequence of
sends to server via socket bytes out of process
(outToServer stream)
• server reads line from socket

iinFromServer
outToServer
• server converts line to
uppercase, sends back to client
• client reads, prints modified
line from socket
inFromUser
(inFromServer stream)

client socket

CT024-3-3 Distributed Computer Systems Socket Programming 9 of 55


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
connectionSocket
close
connectionSocket close
clientSocket

CT024-3-3 Distributed Computer Systems Socket Programming 10 of 55


Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {

public static void main(String argv[]) throws Exception


{
String sentence;
String modifiedSentence;
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream());
attached to socket

CT024-3-3 Distributed Computer Systems Socket Programming 11 of 55


Example: Java client (TCP), cont.

Create BufferedReader inFromServer =


input stream new BufferedReader(new
attached to socket InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();
Send line
to server outToServer.writeBytes(sentence + '\n');

Read line modifiedSentence = inFromServer.readLine();


from server
System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

}
}

CT024-3-3 Distributed Computer Systems Socket Programming 12 of 55


Example: Java server (TCP)
import java.io.*;
import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception


{
String clientSentence;
Create String capitalizedSentence;
welcoming socket
ServerSocket welcomeSocket = new ServerSocket(6789);
at port 6789
while(true) {
Wait, on welcoming
socket for contact Socket connectionSocket = welcomeSocket.accept();
by client
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(connectionSocket.getInputStream()));
to socket

CT024-3-3 Distributed Computer Systems Socket Programming 13 of 55


Example: Java server (TCP),
cont
Create output
stream,
attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';


Write out line
outToClient.writeBytes(capitalizedSentence);
to socket
}
}
} End of while loop,
loop back and wait for
another client connection

CT024-3-3 Distributed Computer Systems Socket Programming 14 of 55


Socket programming with UDP

UDP: no “connection” between client and server


• no handshaking
• sender explicitly attaches IP address and port of destination
application
• server must extract IP address, port viewpoint
of sender from received
datagram UDP provides unreliable transfer
of groups
UDP: transmitted data may be received of bytes
out of order, (“datagrams”)
or lost
between client and server

CT024-3-3 Distributed Computer Systems Socket Programming 15 of 55


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 number close
clientSocket

CT024-3-3 Distributed Computer Systems Socket Programming 16 of 55


Example: Java client (UDP)
import java.io.*;
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket DatagramSocket clientSocket = new DatagramSocket();
Translate
InetAddress IPAddress = InetAddress.getByName("hostname");
hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();

CT024-3-3 Distributed Computer Systems Socket Programming 17 of 55


Example: Java client (UDP), cont.
Create datagram
with data-to-send,
DatagramPacket sendPacket =
length, IP addr,
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
port
Send datagram clientSocket.send(sendPacket);
to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Read datagram
clientSocket.receive(receivePacket);
from server
String modifiedSentence =
new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);


clientSocket.close();
}
}

CT024-3-3 Distributed Computer Systems Socket Programming 18 of 55


Example: Java server (UDP)
import java.io.*;
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];

while(true)
{
Create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagra
m
CT024-3-3 Distributed Computer Systems Socket Programming 19 of 55
Example: Java server (UDP),
cont
String sentence = new String(receivePacket.getData());
Get IP addr
InetAddress IPAddress = receivePacket.getAddress();
port #, of
sender int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another client connection
CT024-3-3 Distributed Computer Systems Socket Programming 20 of 55
Summary on Application Layer
Our study of network apps now
• complete!
application service  specific protocols:
requirements:  http
– reliability, bandwidth,  ftp
delay  smtp, pop3
• client-server paradigm  dns
• Internet transport  socket programming
service model  client/server
– connection-oriented, implementation
reliable: TCP  using tcp, udp sockets
– unreliable, datagrams:
UDP

CT024-3-3 Distributed Computer Systems Socket Programming 21 of 55


Summary on Application Layer
Most importantly: learned about
protocols
• typical request/reply  control vs. data msgs
message exchange:  in-based, out-of-band
– client requests info or
 centralized vs.
service
decentralized
– server responds with
 stateless vs. stateful
data, status code
 reliable vs. unreliable msg
• message formats:
transfer
– headers: fields giving info  “complexity at network
about data edge”
– data: info being  security: authentication
communicated

CT024-3-3 Distributed Computer Systems Socket Programming 22 of 55


Socket Continuation
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)

CT024-3-3 Distributed Computer Systems Socket Programming 24 of 55


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)

CT024-3-3 Distributed Computer Systems Socket Programming 25 of 55


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.
CT024-3-3 Distributed Computer Systems Socket Programming 26 of 55
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.

CT024-3-3 Distributed Computer Systems Socket Programming 27 of 55


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)

CT024-3-3 Distributed Computer Systems Socket Programming 28 of 55


Sockets

Figure 2.6-2: Client socket, welcoming socket and


connection socket

CT024-3-3 Distributed Computer Systems Socket Programming 29 of 55


Socket-programming using TCP
TCP service: reliable byte stream transfer
socket(
) server
socket( ) bind( )
client bind( ) listen( )
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
CT024-3-3 Distributed Computer Systems Socket Programming 30 of 55
Socket programming with TCP
keyboard monitor

Example client-server
app:

inFromUser
input
• client reads line from stream

standard input Client


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

inFromServer
outToServer
output input
stream stream
• server converts line to
uppercase, sends back to client TCP
clientSocket
client socket TCP
• client reads, prints socket

modified line from socket to network from network

(inFromServer stream)
CT024-3-3 Distributed Computer Systems Socket Programming 31 of 55
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 requestconnection 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

CT024-3-3 Distributed Computer Systems Socket Programming 32 of 55


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.

CT024-3-3 Distributed Computer Systems Socket Programming 33 of 55


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());

CT024-3-3 Distributed Computer Systems Socket Programming 34 of 55


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();
}
}

CT024-3-3 Distributed Computer Systems Socket Programming 35 of 55


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()));
CT024-3-3 Distributed Computer Systems Socket Programming 36 of 55
TCPServer.java

DataOutputStream outToClient =
new
DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

}
}
}

CT024-3-3 Distributed Computer Systems Socket Programming 37 of 55


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.

CT024-3-3 Distributed Computer Systems Socket Programming 38 of 55


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

CT024-3-3 Distributed Computer Systems Socket Programming 39 of 55


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

CT024-3-3 Distributed Computer Systems Socket Programming 40 of 55


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()

CT024-3-3 Distributed Computer Systems Socket Programming 41 of 55


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();
CT024-3-3 Distributed Computer Systems Socket Programming 42 of 55
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();
}
}
CT024-3-3 Distributed Computer Systems Socket Programming 43 of 55
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);
CT024-3-3 Distributed Computer Systems Socket Programming 44 of 55
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);

}
}
}

CT024-3-3 Distributed Computer Systems Socket Programming 45 of 55


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

CT024-3-3 Distributed Computer Systems Socket Programming 46 of 55


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());
CT024-3-3 Distributed Computer Systems Socket Programming 47 of 55
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);
CT024-3-3 Distributed Computer Systems Socket Programming 48 of 55
WebServer.java
outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");

if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");

if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");

outToClient.writeBytes("Content-Length: " + numOfBytes + "\


r\n");

outToClient.writeBytes("\r\n");
outToClient.write(fileInBytes, 0, numOfBytes);
connectionSocket.close();
}
else System.out.println("Bad Request Message");
}
}

CT024-3-3 Distributed Computer Systems Socket Programming 49 of 55


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.

CT024-3-3 Distributed Computer Systems Socket Programming 50 of 55


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
CT024-3-3 Distributed Computer Systems Socket Programming 51 of 55
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
CT024-3-3 Distributed Computer Systems Socket Programming 52 of 55
Summary of last section

• Summary of this lecture session covered


about how to develop an secure socket
programming using TCP
• Also learned how the socket reference has
been created

CT024-3-3 Distributed Computer Systems Socket Programming 53 of 55


Question and answer session

Q&A

CT024-3-3 Distributed Computer Systems Socket Programming 54 of 55


What we will cover next

• Time and Global States

CT024-3-3 Distributed Computer Systems Socket Programming 55 of 55

You might also like