You are on page 1of 44

SC250

Computer Networking I

Socket Programming
Prof. Matthias Grossglauser / Dr. Jörg Widmer
LCA/I&C

http://lcawww.epfl.ch

1
Socket programming
Chapter goals:
Learn how to build client/server applications that
communicate using sockets.

 Java sockets
 stream sockets (TCP)
 stream example
 datagram sockets (UDP)
 datagram example
 Multi-threaded servers
 Socket programming in C

2
Recap
Application-level protocols (e.g., HTTP, DNS, SMTP)
use the services of the transport-layer.

Transport-layer provides:
 Communication between processes
 Multiplexing/demultiplexing based on the concept of
ports
 Reliable, in-order delivery: TCP
 connection setup (handshake)
 congestion control
 flow control
 Unreliable, unordered delivery: UDP
 no-frills extension of “best-effort” IP
3
Network API
 Application Programming Interface (API) provides
a set of function types, data structures and
constants
 flexible, simple to use, standardized
 API to access transport protocols of the operating
system is called a socket
 Gives a file-system-like abstraction to the services of the
transport protocols (open, close, read, write)
 BSD sockets (introduced in BSD 4.1 Unix in 1981) are
the most popular Internet sockets: FreeBSD, Linux,
Windows, Mac OS X, ...
 Sockets also used for other purposes (e.g., Unix
interprocess communication)

4
Client/server paradigm
Network applications typically have two components:
 Client:
 initiates contact with the server
 typically requests service from the server
 Server:
 passively listens for clients to connect (on a given port)
 server process usually running all the time

 Applications implementing protocol standard


 use well-known ports and adhere to standard (RFC)
 Proprietary protocol
 complete control over design but should not use well-
known port numbers
5
Socket programming with TCP
 Client must contact  When client creates
server socket: client TCP
 server process must first establishes connection to
be running server TCP
 server must have
 When contacted by client,
created socket (door) server TCP creates new
that welcomes client’s socket for server process
contact to communicate with
client
 Client contacts server  allows server to talk with

by: multiple clients


 creating client-local TCP
application viewpoint
socket
 specifying IP address, TCP provides reliable, in-order
port number of server transfer of bytes (“pipe”)
process between client and server

6
TCP Socket Class
java.lang.Object
 Used for both client and
server |

 New socket is created +--java.net.Socket

using a Socket()
p u b lic c la s s S o c k e t
constructor
 4 constructors + 2 e x te n d s O b je c t
protected
 Connect with creation
co n t r o l l ed b y
co n t r o l l ed b y p r ocess ap p l i cat i o n
ap p l i cat i o n p r ocess
d ev el o p er
d ev el o p er sock et sock et
T CP w i t h T CP w i t h co n t r o l l ed b y
co n t r o l l ed b y
b u f f er s, o p er at i n g
o p er at i n g b u f f er s, In t er n et var i ab l es syst em
syst em var i ab l es

h ost or h ost or
ser v er ser v er
7
TCP ServerSocket Class
 Used for server
java.lang.Object
 New socket is created
|
using a ServerSocket()
constructor +--java.net.ServerSocket
 3 constructors
p u b lic c la s s S e r v e r S o c k e t
 Buffers incoming
connection requests (SYNs) e x te n d s O b je c t
 Use accept() to get the
next connection
co n t r o l l ed b y
co n t r o l l ed b y p r ocess ap p l i cat i o n
ap p l i cat i o n p r ocess
d ev el o p er
d ev el o p er sock et sock et
T CP w i t h T CP w i t h co n t r o l l ed b y
co n t r o l l ed b y
b u f f er s, o p er at i n g
o p er at i n g b u f f er s, In t er n et var i ab l es syst em
syst em var i ab l es

h ost or h ost or
ser v er ser v er 8
Input and Output streams

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

inFromServer
outToServer
 server converts line to pr ocess
uppercase, sends back to
client
 client reads, prints modified
inFromUser
line from socket
(inFromServer stream)
clien t sock et

10
Some remarks on Java I/O streams
 Basic I/O for memory, files, sockets, pipes, ...
 Buffered streams used to reduce accees to data source
(don't forget to flush())
 Data streams used to write Strings, Integers, etc.

11
Client/server socket interaction:
TCP
Server (running on hostid)
create socket,
port=x, for
incom ing request:
Client welcomeSocket =
ServerSocket()
create socket, TCP
connect to hostid, port=x wait for incom ing
clientSocket = connection setup connection request
Socket() connectionSocket =
welcomeSocket.accept()
send request using
clientSocket read request from
connectionSocket

write reply to
read reply from connectionSocket
clientSocket

close close
clientSocket connectionSocket

12
Example: Java client (TCP)

13
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 BufferedReader inFromUser =


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

14
Example: Java client (TCP)

Create BufferedReader inFromServer =


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

sentence = inFromUser.readLine(); aaaa


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

Read line modifiedSentence = inFromServer.readLine();


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

clientSocket.close();

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

class TCPServer {

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


{
String clientSentence;
String capitalizedSentence;
Create
welcoming socket por t 6 78 9
at port 6789 ServerSocket welcomeSocket = new ServerSocket(6789);

Wait, on welcoming while(true) {


socket for contact Socket connectionSocket = welcomeSocket.accept();
by client
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(
to socket
connectionSocket.getInputStream()));

16
Example: Java server (TCP)

Create output
stream, attached DataOutputStream outToClient =
to socket new DataOutputStream(
connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine(); aaaa
capitalizedSentence = clientSentence.toUpperCase() + '\n';
Write out line
AAAA
outToClient.writeBytes(capitalizedSentence);
to socket
}
}
} End of while loop,
loop back and wait for
another client connection

17
Socket programming with UDP

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

18
Client/server socket interaction:
UDP
Server (running on hostid)
Client
create socket,
create socket, port=x, for por t x
clientSocket = incoming request:
DatagramSocket() serverSocket =
Datagram Socket()
por t 2222
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,
close port umber
clientSocket

19
DatagramPacket Class

 Used for both client


and server
 An independent
message (datagram java.lang.Object
packet) is created
|
using a
DatagramPacket() +--java.net.DatagramPacket
constructor
p u b lic fin a l c la s s D a ta g r a m P a c k e t
 4 constructors
e x te n d s O b je c t

20
DatagramSocket Class

 Used for both client and


server
java.lang.Object
 New socket is created
|
using a DatagramSocket
() constructor +--java.net.DatagramSocket

 3 constructors p u b lic c la s s D a ta g r a m S o c k e t

e x te n d s O b je c t

21
Example: Java client (UDP)

22
Example: Java server (UDP)

23
Example: Java client (UDP)
import java.io.*;
import java.net.*;
por t 2222
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
hostname to IP InetAddress IPAddress = InetAddress.getByName("host");
address using DNS

Create input
byte[] sendData = new byte[1024];
and output buffer byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes(); 24
Example: Java client (UDP)
Create datagram
DatagramPacket sendPacket =
with data-to-send,
length, IP addr, port new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);

Send datagram clientSocket.send(sendPacket);


to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Read datagram
from server clientSocket.receive(receivePacket);

String modifiedSentence =
new String(receivePacket.getData());

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


clientSocket.close();
}
}
25
Example: Java server (UDP)
import java.io.*;
import java.net.*;
por t 9 8 76
class UDPServer {
public static void main(String args[]) throws Exception
{
Create
datagram socket
at port 9876 DatagramSocket serverSocket =
new DatagramSocket(9876);

byte[] receiveData = new byte[1024];


byte[] sendData = new byte[1024];

while(true)
{
Create space for
received datagram DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram 26
Example: Java server (UDP)

Get IP addr String sentence = new String(receivePacket.getData());


port #, of
sender InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();


Create datagram
to send to client sendData = capitalizedSentence.getBytes();

Write out DatagramPacket sendPacket =


datagram new DatagramPacket(sendData, sendData.length,
to socket IPAddress, port);

serverSocket.send(sendPacket);
}
}
} End of while loop,
loop back and wait for
another datagram 27
DNS
 InetAddress contains an IP address as String and as int
 Can also be used for explicit DNS lookups:
 InetAddress addr = InetAddress.getByName("www.epfl.ch");
System.out.println(addr.getHostAddress());
 InetAddress addr = InetAddress.getByName("128.178.50.137");
System.out.println(addr.getHostName());
 InetAddress.getAllByName() to get all IP addresses of a host name
 InetAddress is rarely needed:
Socket constructors accept IP addresses, names, and objects of
type InetAddress (implicit DNS)

Note: Java hides/automates many things that


you otherwise have to do "by hand"

28
Reading directly from a URL
 Java provides a number of functions that make programming
much easier:
import java.net.*;
import java.io.*;

public class URLReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
Open URL
as stream BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
Read and
while ((inputLine = in.readLine()) != null)
display the
web page System.out.println(inputLine);
in.close();
}
}
No need to implement HTTP
29
Writing to a URLConnection
 Possible to read and write to a URL (using HTTP)

import java.io.*;
import java.net.*;

public class URLWrite {


public static void main(String[] args) throws Exception {
URL url = new URL(
"http://www.merriam-webster.com/cgi-bin/dictionary");
URLConnection connection = url.openConnection();
allow writing
to the URL
connection.setDoOutput(true);

PrintWriter out = new PrintWriter(


connection.getOutputStream());
out.println("book=Dictionary&va=java&x=0&y=0");
out.close();

30
Writing to a URLConnection (2)

BufferedReader in = new BufferedReader(


new InputStreamReader(
connection.getInputStream()));
String inputLine;
get dictionary while ((inputLine = in.readLine()) != null)
entry on "java" System.out.println(inputLine);

in.close();
}
}

31
Multi-threaded TCP server
To be able to handle a larger number of clients the server
should not process clients in sequence but in parallel.
 Server continuously listens on server socket for client requests
 When accept() returns a socket, start a new thread to handle
the client; hand over the socket to the thread
 Separate threads are usually only used for TCP, not for UDP

Java Threads
servsock = new ServerSocket();  "light-weight" process
 shares memory, etc. with
socket = servsock.accept(); parent (possible conflicts!)
 Extend class Thread and
thread = new Thread(socket); overwrite run() (the "main"
thread.start(); function of a thread)
32
Example: Multi-threaded TCP server
import java.net.*;
import java.io.*;

public class TCPMultiServer {


public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
while (true) {
TCPMultiServerThread thread = new
Create thread TCPMultiServerThread(serverSocket.accept());
for new socket thread.start();
}
serverSocket.close();
}
}
33
Example: Server thread
import java.io.*;
import java.net.*;

public class TCPMultiServerThread extends Thread {


private Socket socket = null;

public TCPMultiServerThread(Socket socket) {


Socket handed
super("TCPMultiServerThread");
over from
main server this.socket = socket;
}

public void run() {


String clientSentence;
String capitalizedSentence;

BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(
to socket
socket.getInputStream()));

34
Example: Server thread (2)

Create output DataOutputStream outToClient =


stream, attached
new DataOutputStream(
to socket
connectionSocket.getOutputStream());

Read in line clientSentence = inFromClient.readLine();


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

Write out line outToClient.writeBytes(capitalizedSentence); AAAA


to socket
close(socket);
}
}

35
Socket programming in C/C++
 C/C++ still significantly faster than Java (although this only
matters if the network isn't the bottleneck)
 Operating system (and therefore the OS side of sockets)
traditionally programmed in C/C++
 C/C++ has a much lower level of abstraction
 C/C++ provides more functionality
 Java does many things automatically that you have to do
by hand in C/C++
 Network programming is easy to get wrong: C/C++ makes
it even a bit harder

36
TCP socket programming in C/C++
Client side Server side
 socket() returns client  socket() returns server
socket ID socket ID
 connect() with server IP  bind() binds socket to
address and port, sends server IP address and port
connection request  listen() waits for
 send() sends data via connection request on server
client socket socket
 recv() receives from  accept() accepts
socket connection request and
 close() closes returns id of a new socket
connection for communication with the
client
 send(), recv(), close()
Note: no explicit connect,
same as for the client socket
listen, and bind in Java
37
UDP socket programming in C/C++
Client side Server side
 socket() returns client  socket() returns server
socket ID socket ID
 sendto() sends data via  bind() binds socket to
client socket; need to server IP address and port
specify IP addr. and port  sendto() sends data via
 recvfrom() receives client socket; need to
from socket specify IP addr. and port
 bind() is optional
 recvfrom() receives from
 close() closes socket socket
 close() closes socket
Note: OS supplies local IP
address and port if bind()
is not used
38
Raw sockets
 Raw sockets allow to create raw IP packets
(bypassing the transport layer)
 use type SOCK_RAW when calling socket()
 no port numbers!
 access similar to datagram sockets
 Necessary e.g. to implement ping (ICMP)
 Only the superuser (root) may create raw
sockets

Note: Raw sockets are not supported in Java

39
Byte ordering
 Byte order of data types depends on the machine
architecture
 host order: 12 34 56 78 (Motorola) big endian
78 56 34 12 (Intel) little endian
 network order: 12 34 56 78
 Conversion functions:
• u_long htonl(u_long hostlong);
• u_short htons(u_short hostshort);
• u_long ntohl(u_long netlong);
• u_short ntohs(u_short netshort);

Note: No need to do this in Java since Java uses


network byte order independently of the machine
40
Example: TCP server in C/C++
#include "inet.h"

int main(int argc, char *argv[]) {


int sd, newSd, rc, i, n, cliLen;

struct sockaddr_in cliAddr, servAddr; // addresses


char msg[MAX_MSG];

sd = socket(AF_INET,SOCK_STREAM,0); // create socket

// bind socket
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(SERVER_PORT);
rc = bind(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));

listen(sd, 5);
41
Example: TCP server in C/C++

// server infinite loop

while(1) {
cliLen = sizeof(cliAddr);
newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen);

n = recv(newSd, msg, MAX_MSG, 0);

msg = str_to_upper(msg); // not implemented here

write(newSd, msg, n);

close(newSd);
} // end of infinite loop
}

42
Socket Programming (TCP & UDP)
 TCP  UDP
Server process must first be running Server process must first be running
and created server socket and have created a socket
Client creates client-local TCP socket Client creates client-local socket and
specifying IP address, port number group data in packets specifying
of server socket each IP address, port number of
Client TCP connects to server TCP server process at server socket

Server creates new TCP socket for


server process to communicate with
client (possibly in new Thread)

TCP provides reliable, in-order transfer UDP provides unreliable transfer of


of bytes between client and server datagrams between client and
Client and Server processes uses server
streams for input and output data Client and Server processes use
datagrams for input and output
data
43
Summary
 Java socket programming
 higher level of abstraction than C/C++
 introduction to most important functions
 more sophisticated functions: access to
socket options, multicast communication,
etc.
 Different communication models
 TCP streams - byte data pipes
 server socket for accepting incoming
connections
 UDP datagrams - isolated messages
 Raw IP sockets (not in Java)
44