socket programming (in java)
TRANSCRIPT
1
Socket Programming (in Java)
ELG/CEG 4183 - February 2003
by Natalija Vlajic
Web Referenceshttp://java.sun.com/docs/books/tutorial/networking/overview/networking.htmlhttp://systems.cs.colorado.edu/grunwald/NetworksResources/Slides/JavaNetworkProgramming.ppt
2
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
3
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 addressneed 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
4
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
5
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 andhinder the usefulness of the service
6
Some Internet Application and their Underlying Transport Protocols
Application Application Protocol Transport Protocol
e-mail smtp TCPremote access telnet TCPWeb http TCPfile transfer ftp TCP
streaming media proprietary TCP or UDPdomain name service DNS TCP or UDP
internet telephony proprietary UDP
7
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)
8
What is a Socket?
• 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
process A process Bnetwork
sockets (IP_address + port)
write
read writeread
9
Socket Programming with TCP
Server Side:� server runs on a specific computer and hasa socket bound to a specific port number� server listens to the socket for a client tomake a connection request
Client Side:� client tries to rendezvous with the server onthe server's machine and port
Server Side:� the server accepts the connection by creatinga new socket bound to a different port
Client Side:� if the connection is accepted, the client usesthe new socket to communicate with the server
Client
Server (running)
Client
Client
Server (running) Client
Client
Client
10
Socket Programming with TCP (cont.)
create socket for incoming requests
welcomeSocket = new ServerSocket()
wait for incoming requests
create new socket
connectionSocket = welcomeSocket.accept()
create socket, connect to server
clientSocket = new Socket()
send request using clientSocket read request from
connectionSocket
write reply to connectionSocket
close connectionSocket
read reply from clientSocket
close clientSocket
TCPconnection
setup
Server (running)
Client
11
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
12
Socket Programming with UDP (cont.)
create socket for incoming datagrams
serverSocket = new DatagramSocket()create socket
clientSocket = new DatagramSocket()
create, address and send datagram using
clientSocket read datagram from
connectionSocket
write reply to connectionSocket specifying client’s
host address & port number
read reply from clientSocket
close clientSocket
Server (running)
Client
13
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... */
return(-1);sa.sin_family= he->h_addrtype; /* host address */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);
}
ServerSocket servsock = new ServerSocket(port, 3);
C codeto establish
a socket
Java codeto establish
a socket
14
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
15
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 socketsA 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 packetDatagram 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.
16
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!
17
Socket Programming with TCP
create socket for incoming requests
welcomeSocket = new ServerSocket()
wait for incoming requests
create new socket
connectionSocket = welcomeSocket.accept()
create socket, connect to server
clientSocket = new Socket()
send request using clientSocket read request from
connectionSocket
write reply to connectionSocket
close connectionSocket
read reply from clientSocket
close clientSocket
TCPconnection
setup
Server (running)
Client
18
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;
ServerSocket welcomeSocket = new ServerSocket(5555);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (newInputStreamReader(connectionSocket.getInputStream()));
create welcomingsocket at port 5555 create welcoming
socket at port 5555
wait for contact-request by clients wait for contact-request by clients
once a request arrives,allocate new socket
once a request arrives,allocate new socket
create & attach input stream to new socket
create & attach input stream to new socket
19
Java TCP-Server (cont.)
DataOutputStream outToClient =new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + ‘\n’;
outToClient.writeBytes(capitalizedSentence);
}}
}
create & attach output stream to new socket
create & attach output stream to new socket
read from socketread from socket
write to socketwrite to socket
end of while loop –wait for another client to connect
end of while loop –wait for another client to connect
20
Java TCP-Client
import java.io.*;import java.net.*;
class TCPClient {
public static void main (String argv[]) throws Exception {
String sentence;String modifiedSentence;
BufferedReader inFromUser = new BufferedReader (newInputStreamReader(System.in));
Socket clientSocket = new Socket(“hostname”,5555);
DataOutputStream outToServer =new DataOutputStream (clientSocket.getOutputStream());
create input streamcreate input stream
create client socket;connect to server
create client socket;connect to server
create output stream attached to socket
create output stream attached to socket
21
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();
}}
Java TCP-Client (cont.)
create input stream attached to socket
create input stream attached to socket
send line to serversend line to server
read line from serverread line from server
22
Socket Programming with UDP
create socket for incoming datagrams
serverSocket = new DatagramSocket()create socket
clientSocket = new DatagramSocket()
create, address and send datagram using
clientSocket read datagram from
connectionSocket
write reply to connectionSocket specifying client’s
host address & port number
read reply from clientSocket
close clientSocket
Server (running)
Client
23
Java UDP-Server (UDP Echo Server)
import java.io.*;import java.net.*;
class UDPServer {
public static void main (String argv[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(7777);
byte[] receiveData = new byte[1024];byte[] sendData = new byte[1024];
while(true) {
DatagramPacket receivePacket =new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
create datagram socket at port 5555 create datagram
socket at port 5555
create space forreceived datagramcreate space for
received datagram
receive datagramreceive datagram
24
Java UDP-Server (cont.)
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase() + ‘\n’;
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
}}
}
get IP address of the sender
get IP address of the sender
get port numberof the sender
get port numberof the sender
create datagramto send to client
create datagramto send to client
write datagramto socket
write datagramto socket
loop back andwait for another
datagram
loop back andwait for another
datagram
25
Java UDP-Client
import java.io.*;import java.net.*;
class UDPClient {
public static void main (String argv[]) throws Exception {
BufferedReader inFromUser = new BufferedReader (newInputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(“localhost”);
byte[] sendData = new byte[1204];byte[] receiveData = new byte[1204];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
create input streamcreate input stream
create client socketcreate client socket
translate hostname toIP address
translate hostname toIP address
26
DatagramPacket sendPacket =new DatagramPacket(sendData,sendData.length,IPAddress,7777);
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.trim());
clientSocket.close();
}}
Java UDP-Client (cont.)
create datagram withdata, length,
IP add., port number
create datagram withdata, length,
IP add., port number
send datagramsend datagram
read datagramread datagram