TCP Socket Programming CPSC 441 Department of Computer Science University of Calgary.

16
TCP Socket Programming CPSC 441 Department of Computer Science University of Calgary
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    221
  • download

    4

Transcript of TCP Socket Programming CPSC 441 Department of Computer Science University of Calgary.

TCP Socket Programming

CPSC 441Department of Computer Science

University of Calgary

CPSC 441 - Application Layer 2

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

SOCK_STREAM TCP connection

oriented, bidirectional

reliable, in-order delivery

Two types of sockets

SOCK_DGRAM

UDP no connection unreliable delivery,

no guarantee on the order

can send/receive

CPSC 441 - Application Layer 4

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

CPSC 441 - Application Layer 5ou

tToS

erve

r

to network from network

inFr

omS

erve

r

inFr

omU

ser

keyboard monitor

Process

clientSocket

inputstream

inputstream

outputstream

TCPsocket

Clientprocess

client TCP socket

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.

CPSC 441 - Application Layer 6

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

CPSC 441 - Application Layer 7

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

CPSC 441 - Application Layer 8

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

CPSC 441 - Application Layer 9

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

10

Threading Mechanisms

Create a class that extends the Thread class

Create a class that implements the Runnable interface

Thread

MyThread

Runnable

MyClass

Thread

(objects are threads) (objects with run() body)

[a] [b]CPSC 441 - Tutorials

11

1st method: Extending Thread class

Create a class by extending Thread class and override run() method: class MyThread extends Thread {

public void run() { // thread body of execution } } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start(); Create and Execute: new MyThread().start();

CPSC 441 - Tutorials

12

Template

class MyThread extends Thread { public void run() { System.out.println(" this thread is running ... "); }}

class ThreadEx1 { public static void main(String [] args ) {

MyThread t = new MyThread(); t.start();

}}

CPSC 441 - Tutorials

13

2nd method: Threads by implementing Runnable interface Create a class that implements the interface Runnable

and override run() method:class MyThread implements Runnable{ ..... public void run() { // thread body of execution }} Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

CPSC 441 - Tutorials

14

Template

class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); }}

class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); t.start(); } }

CPSC 441 - Tutorials

Example of Java Threads

public class ThreadExample implements Runnable {private String greeting;public ThreadExample(String greeting) {

this.greeting = greeting;}public void run( ) {

while(true) {System.out.println(Thread.currentThread( ).getName( ) + ": "+greeting);

try {TimeUnit.MILLISECONDS.sleep(((long) Math.random( ) * 100));

} catch(InterruptedException e) {}

}}public static void main(String [ ] args) {

new Thread(new ThreadExample(“Greeting 1")).start( );new Thread(new ThreadExample(“Greeting 2")).start( );new Thread(new ThreadExample(“Greeting 3")).start( );

}}

Returns reference to current thread

Returns name of thread as string

Suspend the thread; Thread sleeps for random amount of time.

1. Create new instance of ThreadExample with different greeting

2. Passes new instance to the constructor of Thread.

3. Calls new Thread instance's start()Each thread independently executes run() of ThreadExample, while

the main thread terminates. Upon execution an interleaving of three greeting messages is printed 3-15CPSC 441 - Tutorials

Socket Programming, Dan Rubinstein, http://www1.cs.columbia.edu/~danr/courses/6761/Fall00/intro/6761-1b-sockets.ppt

15-441 Socket Programming, www.cs.cmu.edu/afs/cs/academic/class/15441-f01/www/lectures/lecture03.ppt

Network Programming, Geoff Kuenning, www.cs.hmc.edu/~geoff/classes/hmc.cs105.200701/slides/class21_net2.ppt

References