Professional Documents
Culture Documents
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
• 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
• 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.)
5
Some Internet Application and their Underlying
Transport Protocols
6
What is a Port?
process A process B
write network write
read read
Server Side:
server runs on a specific computer and has
a socket bound to a specific port number Client
Client Side:
client tries to rendezvous with the server on
the server's machine and port Client
9
Socket Programming with TCP (cont.)
Server
(running)
Client
TCP
wait for connection
incoming requests setup create socket,
connect to server
create new socket clientSocket = new Socket()
connectionSocket = welcomeSocket.accept()
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
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.)
14
Java Socket Programming
15
Java Client/Server Example
a client reads a line from its standard input (keyboard) and sends the line to the server
the client reads the modified line, and prints the line on its standard output
16
Socket Programming with TCP
Server
(running)
Client
TCP
wait for connection
incoming requests setup create socket,
connect to server
create new socket clientSocket = new Socket()
connectionSocket = welcomeSocket.accept()
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 {
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
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();
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 {
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
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 {
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.)
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 {
create
createclient
clientsocket
socket DatagramSocket clientSocket = new DatagramSocket();
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);
clientSocket.close();
}
}
26