You are on page 1of 26

Socket Programming (in Java)

ELG/CEG 4183 - February 2003

by Natalija Vlajic

Web References
http://java.sun.com/docs/books/tutorial/networking/overview/networking.html
http://systems.cs.colorado.edu/grunwald/NetworksResources/Slides/JavaNetworkProgramming.ppt

1
Networking Basics

• computers running on the Internet communicate to each other using either


Transmission Control (TCP) or the User Datagram (UDP) protocol

• when we write Java programs that communicate over the network, we are
programming at the application layer

• however, to decide which Java classes our programs should use, we need
to understand how TCP and UDP differ

2
UDP (User Datagram Protocol)
• connectionless - sends independent packets of data, called datagrams, from
one computer to another with no guarantees about arrival

• each time a datagram is sent, the local and receiving socket address
need to be sent as well

TCP (Transmission Control Protocol)


• connection-oriented - provides a reliable flow of data between two computers
 data sent from one end of the connection gets to the other end in the same order

• in order to communicate using TCP protocol, a connection must first


be established between the pair of sockets

• once two sockets have been connected, they can be used to transmit
data in both (or either one of the) directions

3
UDP vs. TCP: Which Protocol to Use?

• Overhead
 UDP - every time a datagram is sent, the local and receiving socket address
need to be sent along with it
 TCP - a connection must be established before communications between the
pair of sockets start (i.e. there is a connection setup time in TCP)

• Packet Size
 UDP - there is a size limit of 64 kilobytes per datagram
 TCP - there is no limit; the pair of sockets behaves like streams

• Reliability
 UDP - there is no guarantee that the sent datagrams will be received
in the same order by the receiving socket
 TCP - it is guaranteed that the sent packets will be received in the
order in which they were sent

4
UDP vs. TCP: Which Protocol to Use? (cont.)

• TCP - useful when indefinite amount of data of need to be


transferred ‘in order’ and reliably

 otherwise, we end up with jumbled files or invalid information


 examples: HTTP, ftp, telnet, …

• UDP - useful when data transfer should not be slowed down


by the extra overhead of the reliable connection

 examples: real-time applications


 e.g. consider a clock server that sends the current time to its client
 if the client misses a packet, it doesn't make sense to resend it because the time
will be incorrect when the client receives it on the second try
 the reliability of TCP is unnecessary -it might cause performance degradation and
hinder the usefulness of the service

5
Some Internet Application and their Underlying
Transport Protocols

Application Application Protocol Transport Protocol

e-mail smtp TCP


remote access telnet TCP
Web http TCP
file transfer ftp TCP

streaming media proprietary TCP or UDP


domain name service DNS TCP or UDP

internet telephony proprietary UDP

6
What is a Port?

• generally, a computer has a single physical connection to the network


 this connection is identified by the computer’s 32-bit IP address
 all data destined for a particular computer arrives through this connection

• TCP and UDP use ports to identify a particular process/application


 port = abstract destination point at a particular host
 each port is identified by a positive 16-bit number, in the range 0 - 65,535
 port numbers 0 - 1023 are reserved for well-known services (HTTP - 80, telnet - 23)
7
What is a Socket?

process A process B
write network write
read read

sockets (IP_address + port)

• socket = basic abstraction for network communication


 “end-point of communication” uniquely identified with IP address and port
 example: Socket MyClient = new Socket("Machine name", PortNumber);

 gives a file-system like abstraction to the capabilities of the network


 two end-points communicate by “writing” into and “reading” out of socket

 there are two types of transport via sockets


 reliable, byte-stream oriented
 unreliable datagram
8
Socket Programming with TCP

Server Side:
 server runs on a specific computer and has
a socket bound to a specific port number Client

 server listens to the socket for a client to Server


make a connection request (running)
Client

Client Side:
 client tries to rendezvous with the server on
the server's machine and port Client

Server Side: Client


 the server accepts the connection by creating
a new socket bound to a different port Server
(running) Client
Client Side:
 if the connection is accepted, the client uses
the new socket to communicate with the server Client

9
Socket Programming with TCP (cont.)

Server
(running)
Client

create socket for


incoming requests
welcomeSocket = new ServerSocket()

TCP
wait for connection
incoming requests setup create socket,
connect to server
create new socket clientSocket = new Socket()
connectionSocket = welcomeSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket
read reply from
clientSocket

close
connectionSocket
close
clientSocket
10
Socket Programming with UDP

• all clients use the same socket to communicate with the server
 packets of data (datagrams) are exchanged
 no new sockets need to be created

Client

Server
(running)
Client

Client

11
Socket Programming with UDP (cont.)

Server
(running)
Client

create socket for


incoming datagrams
serverSocket = new DatagramSocket()
create socket
clientSocket = new DatagramSocket()

create, address and


read datagram from send datagram using
connectionSocket clientSocket

write reply to
connectionSocket
specifying client’s
host address &
read reply from
port number
clientSocket

close
clientSocket
12
C- vs. Java- Socket Programming
int set_up_socket(u_short port) {
char myname[MAXHOSTNAME+1];
int s;
struct sockaddr_in sa;
struct hostent *he;
bzero(&sa,sizeof(struct sockaddr_in)); /* clear the address */
gethostname(myname,MAXHOSTNAME); /* establish identity */
he= gethostbyname(myname); /* get our address */
if (he == NULL) /* if addr not found... */
C code return(-1);
to establish sa.sin_family= he->h_addrtype; /* host address */
a socket sa.sin_port= htons(port); /* port number */
if ((s= socket(AF_INET,SOCK_STREAM,0)) <0) /* finally, create socket */
return(-1);
if (bind(s, &sa, sizeof(sa), 0) < 0) {
close(s);
return(-1); /* bind address to socket */
}
listen(s, 3); /* max queued connections */
return(s);
}

Java code
to establish ServerSocket servsock = new ServerSocket(port, 3);
a socket
13
C- vs. Java- Socket Programming (cont.)

• Java keeps all the socket complexity “under the cover”


 it does not expose the full range of socket possibilities
 but, it enables that sockets be opened/used as easily as a file would be opened/
used

• by using the java.net.Socket class instead of relying on native code, Java


programs can communicate over the network in a platform-independent fashion

14
Java Socket Programming

• all classes related to sockets are in java.net package

 Socket class - implements client sockets (also called just "sockets")

 ServerSocket class - implements server sockets


A server socket waits for requests to come in over the network. It performs some operation based on that
request, and then possibly returns a result to the requester.

 DatagramSocket class - socket for sending and receiving datagram packets

 DatagramPacket class - represents a datagram packet


Datagram packets are used to implement a connectionless packet delivery service. Multiple packets sent
from one machine to another might be routed differently, and might arrive in any order.

 InetAddress class - represents an Internet Protocol (IP) address

 MulticastSocket class - useful for sending and receiving IP multicast packets.


A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining "groups" of other
multicast hosts on the internet. A multicast group is specified by a class D IP address.

15
Java Client/Server Example

 a client reads a line from its standard input (keyboard) and sends the line to the server

 the server reads the line

 the server converts the line to uppercase

 the server sends the modified line back to the client

 the client reads the modified line, and prints the line on its standard output

Implement above client/server scenario using both TCP and UDP!

16
Socket Programming with TCP

Server
(running)
Client

create socket for


incoming requests
welcomeSocket = new ServerSocket()

TCP
wait for connection
incoming requests setup create socket,
connect to server
create new socket clientSocket = new Socket()
connectionSocket = welcomeSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket
read reply from
clientSocket

close
connectionSocket
close
clientSocket
17
Java TCP-Server (TCP Echo Server)

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

class TCPServer {

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

String clientSentence;
String capitalizedSentence;
create
createwelcoming
welcoming
socket
socketat
atport
port5555
5555 ServerSocket welcomeSocket = new ServerSocket(5555);

wait
waitfor
forcontact-
contact- while(true) {
request
requestby
byclients
clients

Socket connectionSocket = welcomeSocket.accept();


once
onceaarequest
requestarrives,
arrives,
allocate
allocatenew
newsocket
socket
BufferedReader inFromClient = new BufferedReader (new
InputStreamReader(connectionSocket.getInputStream()));
create
create&&attach
attachinput
input
stream to new socket
stream to new socket 18
Java TCP-Server (cont.)

create
create&&attach
attachoutput
output DataOutputStream outToClient =
stream to new socket
stream to new socket
new DataOutputStream(connectionSocket.getOutputStream());

read
readfrom
fromsocket
socket clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + ‘\n’;

write
writeto
tosocket
socket
outToClient.writeBytes(capitalizedSentence);

}
}
}

end
endofofwhile
whileloop
loop––
wait for another
wait for another
client
clientto
toconnect
connect

19
Java TCP-Client

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

class TCPClient {

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

String sentence;
String modifiedSentence;
create
createinput
inputstream
stream
BufferedReader inFromUser = new BufferedReader (new
InputStreamReader(System.in));
create
createclient
clientsocket;
socket;
connect
connectto
toserver
server Socket clientSocket = new Socket(“hostname”,5555);

DataOutputStream outToServer =
create
createoutput
outputstream
stream new DataOutputStream (clientSocket.getOutputStream());
attached
attachedto
tosocket
socket

20
Java TCP-Client (cont.)

create
createinput
inputstream
stream BufferedReader inFromServer = new BufferedReader (new
attached
attachedtotosocket
socket InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();

send
sendline
lineto
toserver
server outToServer.writeBytes(sentence + ‘\n’);

modifiedSentence = inFromServer.readLine();

read
readline
linefrom
fromserver
server System.out.println(“FROM SERVER: “+modifiedSentence);

clientSocket.close();

}
}

21
Socket Programming with UDP

Server
(running)
Client

create socket for


incoming datagrams
serverSocket = new DatagramSocket()
create socket
clientSocket = new DatagramSocket()

create, address and


read datagram from send datagram using
connectionSocket clientSocket

write reply to
connectionSocket
specifying client’s
host address &
read reply from
port number
clientSocket

close
clientSocket
22
Java UDP-Server (UDP Echo Server)

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

class UDPServer {

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


create
createdatagram
datagram
socket
socket atport
at port5555
5555 DatagramSocket serverSocket = new DatagramSocket(7777);

byte[] receiveData = new byte[1024];


byte[] sendData = new byte[1024];

while(true) {
create
createspace
spacefor
for
received DatagramPacket receivePacket =
receiveddatagram
datagram
new DatagramPacket(receiveData, receiveData.length);

receive
receivedatagram
datagram serverSocket.receive(receivePacket);

23
Java UDP-Server (cont.)

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


get
getIP
IPaddress
address
of the sender
of the sender
InetAddress IPAddress = receivePacket.getAddress();

get
getport
portnumber
number
int port = receivePacket.getPort();
of
of thesender
the sender
String capitalizedSentence = sentence.toUpperCase() + ‘\n’;

sendData = capitalizedSentence.getBytes();
create
createdatagram
datagram
to
tosend
sendto
toclient
client
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length,IPAddress,port);
write
writedatagram
datagram
to
tosocket
socket
serverSocket.send(sendPacket);

loop
}
loopback
backand
and
wait
wait foranother
for another }
datagram
datagram }

24
Java UDP-Client

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

class UDPClient {

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


create
createinput
inputstream
stream BufferedReader inFromUser = new BufferedReader (new
InputStreamReader(System.in));

create
createclient
clientsocket
socket DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getByName(“localhost”);


translate
translatehostname
hostnameto
to
IP address
IP address
byte[] sendData = new byte[1204];
byte[] receiveData = new byte[1204];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes(); 25
Java UDP-Client (cont.)

create
createdatagram
datagramwith
with DatagramPacket sendPacket =
data,
data,length,
length, new DatagramPacket(sendData,sendData.length,IPAddress,7777);
IP
IPadd.,
add.,port
portnumber
number

send clientSocket.send(sendPacket);
senddatagram
datagram

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);

read
readdatagram
datagram clientSocket.receive(receivePacket);

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

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

clientSocket.close();

}
}

26

You might also like