Top Banner
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application Layer – Socket Programming in Java Reading: Chapter 2 – Still
24

1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

Dec 14, 2015

Download

Documents

Katrina Baldwin
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

1

CSCD 330Network ProgrammingSpring 2014

Some Material in these slides from J.F Kurose and K.W. RossAll material copyright 1996-2007

Lecture 7Application Layer – Socket Programming in Java

Reading: Chapter 2 – Still

Page 2: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

Review Client/ServerProgramming

• So far,• Host has IP Address 146.187.134.22

• Network Layer identifier • Every network “device” has this identifier

• Phone, Toaster, etc.

• Processes running on Hosts • Assigned a port number• Port numbers identifiers for processes• Some port numbers reserved 1 - 1023

• System reserves these• Other port numbers reserved for widely recognized processeshttp://en.wikipedia.org/wiki/

List_of_TCP_and_UDP_port_numbers#Dynamic.2C_private_or_ephemeral_ports:_49152.E2.80.9365535

Firefox HTTP 80

Page 3: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

Review Client/Server Programming

• Communication Between Client/Server• Uses object, “Socket”• Socket is the API between a program and the

TCP/IP stack of the OS• It has an input stream and an output stream built

in to it• Both the client and server define different ends of

this socket• Link to the Java .net Package API

http://download.oracle.com/javase/1.4.2/docs/api/java/net /Socket.html

Page 4: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

TCP/IP Client/Server

• How this works in Java• Server Socket

1. Binds socket to specific port number

2. Listens for incoming connections on that port

3. When connection attempted, it accepts connection, creates a regular socket for communication to client

4. Port number is different and selected by stack software

Page 5: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

TCP/IP Client/Server

• Java Code for Server ss = new ServerSocket (port);// Loop foreverWhile (true) {

// Get a connectionSocket newSocket = ss.accept

();// Deal with the connection// ....

}

Server socket listens on a port

Inside loop waits for connection

Creates a new socket object representing new connectionWhat is not obvious is that the new connection is through a different port number

Page 6: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

TCP/IP Client/Server• Java code for Client, Send/Receive Data// Create a socket for communicating with server Socket clientSocket = new Socket ("hostname", 6789);

// Create data streams for communicating through the socket BufferedReader in = new BufferedReader

(new InputStreamReader (clientSocket.getInputStream ());

PrintWriter out = new PrintWriter (clientSocket.getOutputStream ());

System.out.println (in.readLine ()); // Print output to screen

Then, create streams to send input and get it back from server

Create a client TCP socket, with host and port

Page 7: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

7

Example: Java client (TCP)

import java.io.*; import java.net.*; class TCPClient {

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

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("hostname", 6789);

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

Createinput stream

Create client socket,

connect to server

Createoutput stream

attached to socket

Page 8: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

8

Example: Java client (TCP)

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(); } }

Createinput stream

attached to socket

Send lineto server

Read linefrom server

Page 9: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

9

Example: Java server (TCP)import java.io.*; import java.net.*;

class TCPServer {

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

ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

Createwelcoming socket

at port 6789

Waits, on welcomingsocket for contact

by client

Create inputstream, attached

to socket

Page 10: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

10

Example: Java server (TCP)

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

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

outToClient.writeBytes(capitalizedSentence); } } }

Read in linefrom socket

Create outputstream,

attached to socket

Write out lineto socket

End of while loop,loop back and wait foranother client connection

Page 11: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

UDP

Page 12: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

12

UDP Socket ProgrammingUDP no real “connection” between client and

server• No handshaking• Sender attaches IP address and destination

port to each packet• Server must extract IP address and port of

sender from received packet, so answer can be sent back!

UDP, transmitted data may be

– Received out of order, or

– Lost

Page 13: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

13

Client/server socket interaction: UDP

closeclientSocket

Server (running on hostid)

read reply fromclientSocket

create socket,clientSocket = DatagramSocket()

Client

Create, address (hostid, port=50)send datagram request using clientSocket

create socket,port=50, forincoming request:serverSocket = DatagramSocket()

read request fromserverSocket

write reply toserverSocketspecifying clienthost address,port number

Page 14: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

14

UDP Summary

• No connection setup – no “pipe”

• Main Differences, TCP:1. Each batch of bytes sent with attached address information2. No special ServerSocket class in java

Client

Server

Page 15: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

UDP Summary

• Create a Packet • Push it out into the network through a socket• Server accepts the packet addressed to him

• Mail is a lot like UDP• Each letter needs the address of the destination• Independent letters sent to the same address

Page 16: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

16

Java Classes for UDP• Datagrams for connectionless protocol• Two classes implement datagrams in Java:

• java.net.DatagramPacket• java.net.DatagramSocket

• DatagramPacket is actual packet of information, an array of bytes, that is transmitted over the network.

• DatagramSocket is socket that sends and receives DatagramPackets across the network.

• Think of DatagramPacket as a letter and DatagramSocket as the mailbox that the mail carrier uses to pick up and drop off your letters

• Need both classes for UDP sockets

Page 17: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

17

Java Classes for UDP

• DatagramPacket class provides programmer with two constructors. • First is for DatagramPackets that receive dataConstructor needs

Array to store the data Amount of data to receive

• Second is for DatagramPackets that send data

Constructor needs Array to store the data Amount of data to send Plus destination address and port

number

Page 18: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

18

Java Classes for UDP• DatgramSocket represents connectionless socket

It provides two constructors, 1. Programmer can specify a port OR 2. Allow system to randomly use a port

• Methods• Two most important methods, send() and receive()• Each takes an argument of a constructed

DatagramPacket

• send() method• Data in packet is sent to specified host and port

• receive() method • Will block execution until a packet is received by underlying socket, then data copied into packet provided

Page 19: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

19

Sentence Capitalizer (Again)Example: Java client (UDP)

import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

Createinput stream

Create client socket

Translate hostname to IP

address using DNS

Keyboard

Page 20: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

20

Example: Java client (UDP), cont.

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 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); clientSocket.close(); }

}

Create datagram with data-to-send,

length, IP addr, port

Send datagramto server

Read datagramfrom server

Page 21: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

21

Sentence Capitalizer (Again)Example: Java server (UDP)

import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

Createdatagram socket

at port 9876

Create space forreceived datagram

Receivedatagram

Page 22: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

22

Example: Java server (UDP), cont

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } }

}

Get IP addrport #, of

sender

Write out datagramto socket

End of while loop,loop back and wait foranother datagram

Create datagramto send to client

Page 23: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

23

Summary

• Brief coverage of Java sockets - TCP/UDP

• Should be enough to get started• Examples will be available as links on the

main class page

• Will cover threads next • First assignment will be a multi-

threaded Web Server …• Also, will practice client-server in the

lab• Do read references in RelatedLinks for

more information

Page 24: 1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1996-2007 Lecture 7 Application.

24

Assignment is up, WebServer