35
1 CS: 4244 Internet Programming Sockets Programming Dr. Eli Tilevich January 29, 2007

1 CS: 4244 Internet Programming Sockets Programming Dr. Eli Tilevich January 29, 2007

Embed Size (px)

Citation preview

1

CS: 4244 Internet ProgrammingSockets Programming

Dr. Eli TilevichJanuary 29, 2007

2

Chapter 2Application Layer

Computer Networking: A Top Down Approach Featuring the Internet, 3rd edition. Jim Kurose, Keith RossAddison-Wesley, July 2004.

A note on the use of these ppt slides:We’re making these slides freely available to all (faculty, students, readers). They’re in PowerPoint form so you can add, modify, and delete slides (including this one) and slide content to suit your needs. They obviously represent a lot of work on our part. In return for use, we only ask the following: If you use these slides (e.g., in a class) in substantially unaltered form, that you mention their source (after all, we’d like people to use our book!) If you post any slides in substantially unaltered form on a www site, that you note that they are adapted from (or perhaps identical to) our slides, and note our copyright of this material.

Thanks and enjoy! JFK/KWR

All material copyright 1996-2005J.F Kurose and K.W. Ross, All Rights Reserved

3

Sockets

process sends/receives messages to/from its socket

socket analogous to door sending process shoves

message out door sending process relies on

transport infrastructure on other side of door which brings message to socket at receiving process

process

TCP withbuffers,variables

socket

host orserver

process

TCP withbuffers,variables

socket

host orserver

Internet

controlledby OS

controlled byapp developer

API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later)

4

Socket programming

Socket API introduced in BSD4.1 UNIX,

1981 explicitly created, used,

released by apps client/server paradigm two types of transport

service via socket API: unreliable datagram reliable, byte stream-

oriented

a host-local, application-created,

OS-controlled interface (a “door”) into which

application process can both send and

receive messages to/from another

application process

socket

Goal: learn how to build client/server application that communicate using sockets

5

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

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperating

system

host orserver

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperatingsystem

host orserver

internet

6

Socket programming with TCPClient must contact server server process must first

be running server must have created

socket (door) that welcomes client’s contact

Client contacts server by: creating client-local TCP

socket specifying IP address, port

number of server process When client creates socket:

client TCP establishes connection to server TCP

When contacted by client, server TCP creates new socket for server process to communicate with client allows server to talk

with multiple clients source port numbers

used to distinguish clients

TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server

application viewpoint

7

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.

8

Socket programming with TCP

Example client-server app:

1) client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)

2) server reads line from socket3) server converts line to

uppercase, sends back to client

4) client reads, prints modified line from socket (inFromServer stream)

outT

oSer

ver

to network from network

inFr

omS

erve

r

inFr

omU

ser

keyboard monitor

Process

clientSocket

inputstream

inputstream

outputstream

TCPsocket

Clientprocess

client TCP socket

9

Client/server socket interaction: TCP

wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()

create socket,port=x, forincoming request:welcomeSocket =

ServerSocket()

create socket,connect to hostid, port=xclientSocket =

Socket()

closeconnectionSocket

read reply fromclientSocket

closeclientSocket

Server (running on hostid) Client

send request usingclientSocketread request from

connectionSocket

write reply toconnectionSocket

TCP connection setup

10

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

11

Example: Java client (TCP), cont.

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

12

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

Wait, on welcomingsocket for contact

by client

Create inputstream, attached

to socket

13

Example: Java server (TCP), cont

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

14

TCP/IP Sockets in Java: Practical Guide for Programmers

Kenneth L. Calvert Michael J. Donahoo

15

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

Server starts by getting ready to receive client connections…

16

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

ServerSocket servSock = new ServerSocket(servPort);

17

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

for (;;) { Socket clntSock = servSock.accept();

18

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

Server is now blocked waiting for connection from a client

19

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

Later, a client decides to talk to the server…

20

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

Socket socket = new Socket(server, servPort);

21

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

OutputStream out = socket.getOutputStream(); out.write(byteBuffer);

22

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

Socket clntSock = servSock.accept();

23

TCP Client/Server Interaction

Client1. Create a TCP socket2. Communicate3. Close the connection

Server1. Create a TCP socket2. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

InputStream in = clntSock.getInputStream(); recvMsgSize = in.read(byteBuffer);

24

TCP Client/Server Interaction

Client1. Create a TCP socket2. Establish connection3. Communicate4. Close the connection

Server1. Create a TCP socket2. Bind socket to a port3. Set socket to listen4. Repeatedly:

a. Accept new connectionb. Communicatec. Close the connection

close(sock); close(clntSocket)

25

TCP Tidbits

Clientout.write(“Hello Bob”)

in.read() -> “Hi Jane”

Server

in.read() -> “Hello ”in.read() -> “Bob”out.write(“Hi ”)out.write(“Jane”)

Client knows server address and port No correlation between send() and recv()

26

Closing a Connection

close() used to delimit communication Analogous to EOF

Clientout.write(string)

while (not received entire string)in.read(buffer)out.write(buffer)

close(socket)

Server

in.read(buffer)while(client has not closed connection)

out.write(buffer)in.read(buffer)

close(client socket)

27

TCP Tidbits

Clientout.write(“Hello Bob”)

in.read() -> “Hi Jane”

Server

in.read() -> “Hello ”in.read() -> “Bob”out.write(“Hi ”)out.write(“Jane”)

Client knows server address and port No correlation between send() and recv()

28

Closing a Connection

close() used to delimit communication Analogous to EOF

Clientout.write(string)

while (not received entire string)in.read(buffer)out.write(buffer)

close(socket)

Server

in.read(buffer)while(client has not closed connection)

out.write(buffer)in.read(buffer)

close(client socket)

29

Constructing Messages

…beyond simple strings

30

TCP/IP Byte Transport

TCP/IP protocols transports bytes

Application protocol provides semantics

Application

TCP/IP

byte stream

Application

TCP/IP

byte streamHere are

some bytes. I don’t know what they

mean.

I’ll pass these to the app. It knows what to

do.

31

Application Protocol

Encode information in bytes Sender and receiver must agree on

semantics Data encoding

Primitive types: strings, integers, and etc. Composed types: message with fields

32

Primitive Types

String Character encoding: ASCII, Unicode, UTF Delimit: length vs. termination character

M o m \n

3 77 111 109

0 77 0 111 0 109 0 10

33

Integer Strings of character encoded decimal digits

• Advantage: 1. Human readable2. Arbitrary size

• Disadvantage: 1. Inefficient2. Arithmetic

manipulation

Primitive Types

49 55 57 57 56 55 48 10

‘1’ ‘7’ ‘9’ ‘9’ ‘8’ ‘7’ ‘0’ \n

34

Primitive Types

Integer Native representation

Network byte order (Big-Endian)• Use for multi-byte, binary data exchange• htonl(), htons(), ntohl(), ntohs()

0 0 92 246 4-bytetwo’s-complement integer

23,798

246 92 0 0Big-Endian

Little-Endian

35

Message Composition

Message composed of fields

Fixed-length fields

Variable-length fields

integer short short

M i k e 1 2 \n