Professional Documents
Culture Documents
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
6
TCP Socket Class
java.lang.Object
Used for both client and
server |
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 {
14
Example: Java client (TCP)
clientSocket.close();
}
}
15
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
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
20
DatagramSocket Class
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 modifiedSentence =
new String(receivePacket.getData());
while(true)
{
Create space for
received datagram DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram 26
Example: Java server (UDP)
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)
28
Reading directly from a URL
Java provides a number of functions that make programming
much easier:
import java.net.*;
import java.io.*;
import java.io.*;
import java.net.*;
30
Writing to a URLConnection (2)
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.*;
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(
to socket
socket.getInputStream()));
34
Example: Server thread (2)
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
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);
// 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++
while(1) {
cliLen = sizeof(cliAddr);
newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen);
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