JavaSockets Beginning

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Data Communication & Networks

G22.2262-001

Session 10 - Main Theme


Java Sockets

Dr. Jean-Claude Franchitti

New York University


Computer Science Department
Courant Institute of Mathematical Sciences

1
Agenda
 Internet Transport-Layer Protocols
 Multiplexing / Demultiplexing
 Socket Programming

2
Part I

Internet Transport-Layer Protocols

3
Internet Transport-Layer Protocols
• Reliable, in-order application
transport
delivery TCP network
data link
physical network
– congestion control network
data link
physical
data link
– flow control physical

network
– connection setup data link
physical network

• Unreliable, unordered data link


physical

delivery: UDP network


data link
physical
– no-frills extension of
“best-effort” IP application
transport
network
• Services not available: data link
physical

– delay guarantees
– bandwidth guarantees 4
Part II

Multiplexing / Demultiplexing

5
Multiplexing/Demultiplexing
Demultiplexing at rcv host: Multiplexing at send host:
gathering data from multiple
delivering received segments
sockets, enveloping data with
to correct socket
header (later used for
demultiplexing)
= socket = process

application P3 P1
P1 application P2 P4 application

transport transport transport

network network network

link link link

physical physical physical

host 2 host 3
host 1
6
How Demultiplexing Works
• Host receives IP datagrams 32 bits
– each datagram has source IP
source port # dest port #
address, destination IP address
– each datagram carries 1
transport-layer segment other header fields
– each segment has source,
destination port number
(recall: well-known port application
numbers for specific data
applications) (message)
• Host uses IP addresses &
port numbers to direct
TCP/UDP segment format
segment to appropriate
socket
7
Connectionless Demultiplexing
• Create sockets with • When host receives UDP
port numbers: segment:
DatagramSocket – checks destination port
mySocket1 = new
number in segment
DatagramSocket(99111)
; – directs UDP segment to
DatagramSocket socket with that port
mySocket2 = new number
DatagramSocket(99222)
; • IP datagrams with
• UDP socket identified by different source IP
two-tuple: addresses and/or source
(dest IP address, dest port number) port numbers directed to
same socket
8
Connectionless Demux (cont.)

DatagramSocket serverSocket = new DatagramSocket(6428);

P2 P1
P1
P3

SP: 6428 SP: 6428


DP: 9157 DP: 5775

SP: 9157 SP: 5775


client DP: 6428 DP: 6428 Client
server
IP: A IP: C IP:B

SP provides “return address”


9
Connection-Oriented Demux
• TCP socket identified • Server host may support
by 4-tuple: many simultaneous TCP
– source IP address sockets:
– source port number – each socket identified by its
– dest IP address own 4-tuple
– dest port number • Web servers have different
• recv host uses all four sockets for each
values to direct connecting client
segment to appropriate – non-persistent HTTP will
socket have different socket for
each request

10
Connection-Oriented Demux (cont.)

P1 P4 P5 P6 P2 P1P3

SP: 5775
DP: 80
S-IP: B
D-IP:C

SP: 9157 SP: 9157


client DP: 80 DP: 80 Client
server
IP: A S-IP: A
IP: C S-IP: B IP:B
D-IP:C D-IP:C

11
Part III

Socket Programming

12
Socket Programming
Goal: learn how to build client/server application that
communicate using sockets
Socket API
socket
• introduced in BSD4.1
UNIX, 1981 a host-local,
application-created,
• explicitly created, used, OS-controlled interface
released by apps (a “door”) into which
• client/server paradigm application process can
both send and
• two types of transport receive messages to/from
service via socket API: another application
process
– unreliable datagram
– reliable, byte stream-
oriented 13
Socket Programming Using TCP
Socket: a door between application process and end-end-
transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one process
to another

controlled by
controlled by process application
application process
developer
developer socket socket
TCP with TCP with controlled by
controlled by
buffers, operating
operating buffers, internet system
system variables variables

host or host or
server server
14
Socket Programming With TCP
Client must contact server • When contacted by client,
• server process must first be server TCP creates new socket
running for server process to
• server must have created socket communicate with client
(door) that welcomes client’s
contact – allows server to talk with
multiple clients
Client contacts server by: – source port numbers used
• creating client-local TCP socket
to distinguish clients (more
• specifying IP address, port
in Chap 3)
number of server process
application viewpoint
• When client creates socket:
client TCP establishes TCP provides reliable, in-order
connection to server TCP transfer of bytes (“pipe”)
between client and server
15
Stream Jargon
• A stream is a sequence of
characters that flow into or
out of a process
• An input stream is attached
to some input source for
the process (e.g., keyboard
or socket)
• An output stream is
attached to an output
source (e.g., monitor or
socket)
16
Socket Programming With TCP
Example client-server app: keyboard monitor

1) client reads line from

inFromUser
standard input input
stream
(inFromUser stream) , Client
sends to server via socket Process
process
(outToServer stream)
2) server reads line from socket

inFromServer
outToServer
3) server converts line to
output input
uppercase, sends back to stream stream

client
client TCP
clientSocket
4) client reads, prints modified socket TCP
socket
line from socket
to network from network
(inFromServer stream)
17
Client/Server Socket Interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
clientSocket =
connectionSocket =
Socket()
welcomeSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket
read reply from
clientSocket
close
connectionSocket close
clientSocket 18
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
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream());
attached to socket
19
Example: Java Client (TCP), cont.

Create BufferedReader inFromServer =


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

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

Read line modifiedSentence = inFromServer.readLine();


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

clientSocket.close();

}
}
20
Example: Java Server (TCP)
import java.io.*;
import java.net.*;

class TCPServer {

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


{
String clientSentence;
Create String capitalizedSentence;
welcoming socket
ServerSocket welcomeSocket = new ServerSocket(6789);
at port 6789
while(true) {
Wait, on welcoming
socket for contact Socket connectionSocket = welcomeSocket.accept();
by client
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(connectionSocket.getInputStream()));
to socket
21
Example: Java Server (TCP), cont.

Create output
stream, attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine();

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


Write out line
outToClient.writeBytes(capitalizedSentence);
to socket
}
}
} End of while loop,
loop back and wait for
another client connection

22
Socket Programming With UDP
UDP: no “connection”
between client and server
• no handshaking
• sender explicitly attaches IP application viewpoint
address and port of UDP provides unreliable transfer
destination to each packet of groups of bytes (“datagrams”)
• server must extract IP between client and server
address, port of sender from
received packet

UDP: transmitted data may


be received out of order,
or lost 23
Client/Server Socket Interaction: UDP
Server (running on hostid) Client

create socket, create socket,


port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket

write reply to
serverSocket
specifying client read reply from
clientSocket
host address,
port number close
clientSocket

24
Example: Java Client (UDP)
keyboard monitor

inFromUser
input
stream

Client
Process Input: receives
process
packet (TCP
received “byte
Output: sends packet
stream”)
(TCP sent “byte

receivePacket
sendPacket
stream”) UDP UDP
packet packet

client UDP
clientSocket
socket UDP
socket

to network from network

25
Example: Java Client (UDP)
import java.io.*;
import java.net.*;

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
InetAddress IPAddress = InetAddress.getByName("hostname");
hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();
26
Example: Java Client (UDP), cont.
Create datagram
with data-to-send, DatagramPacket sendPacket =
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
clientSocket.receive(receivePacket);
from server
String modifiedSentence =
new String(receivePacket.getData());

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


clientSocket.close();
}
}

27
Example: Java Server (UDP)
import java.io.*;
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];

while(true)
{
Create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram
28
Example: Java Server (UDP), cont.
String sentence = new String(receivePacket.getData());
Get IP addr
InetAddress IPAddress = receivePacket.getAddress();
port #, of
sender int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram 29
Part IV

Conclusion

30
Assignment & Readings

 Final Project (due 05/19/15)


 Assigned after the last class
 Readings
 Java.Net Package Documentation on Sun’s Java Web site
 http://java.sun.com/docs/books/tutorial/networking/sockets/

31
Next Session:
IP Multicast

32

You might also like