Transcript document

TCP Socket Programming
CPSC 441
Department of Computer Science
University of Calgary
Socket programming
Goal: learn how to build client/server application that
communicate using sockets
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 streamoriented
socket
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
CPSC 441 - Application Layer
2
Two types of sockets
 SOCK_STREAM
 TCP
 connection oriented,
bidirectional
 reliable, in-order
delivery
 SOCK_DGRAM
UDP
 no connection
 unreliable delivery, no
guarantee on the order
 can send/receive

Socket-programming using TCP
Socket: a door between application process and endend-transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one
process to another
controlled by
application
developer
controlled by
operating
system
process
process
socket
TCP with
buffers,
variables
host or
server
internet
socket
TCP with
buffers,
variables
controlled by
application
developer
controlled by
operating
system
host or
server
CPSC 441 - Application Layer
4
Stream jargon
keyboard
monitor
output
stream
inFromServer
Client
Process
process
input
stream
outToServer
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.
inFromUser
 A stream is a sequence of
input
stream
client
TCP
clientSocket
socket
to network
TCP
socket
from network
CPSC 441 - Application Layer
5
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
Create
client socket,
connect to server
Create
output stream
attached to socket
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname“,6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
CPSC 441 - Application Layer
6
Example: Java client (TCP), cont.
Create
input stream
attached to socket
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
Send line
to server
outToServer.writeBytes(sentence + '\n');
Read line
from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
CPSC 441 - Application Layer
7
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
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()));
CPSC 441 - Application Layer
8
Example: Java server (TCP), cont
Create output
stream, attached
to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
Write out line
to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
End of while loop,
loop back and wait for
another client connection
CPSC 441 - Application Layer
9
Threading Mechanisms
 Create a class that extends the Thread
class
 Create a class that implements the
Runnable interface
Thread
MyThread
(objects are threads)
[a]
10
Runnable
Thread
MyClass
(objects with run() body)
[b]
CPSC 441 - Tutorials
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();
11
CPSC 441 - Tutorials
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();
}
}
12
CPSC 441 - Tutorials
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();
13
CPSC 441 - Tutorials
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();
}
}
14
CPSC 441 - Tutorials
Example of Java Threads
public class ThreadExample implements Runnable {
private String greeting;
public ThreadExample(String greeting) {
this.greeting = greeting;
Returns
}
reference to
public void run( ) {
current thread
while(true) {
System.out.println(Thread.currentThread( ).getName( ) + ": "+greeting);
Returns
name of
thread as
string
try {
Suspend the
TimeUnit.MILLISECONDS.sleep(((long) Math.random( ) * 100));
thread; Thread
} catch(InterruptedException e) {
sleeps for random
}
amount of time.
}
1.
Create new instance of
}
ThreadExample with different
public static void main(String [ ] args) {
greeting
new Thread(new ThreadExample(“Greeting 1")).start( );
new Thread(new ThreadExample(“Greeting 2")).start( );
2. Passes new instance to the
new Thread(new ThreadExample(“Greeting 3")).start( );
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
CPSC 441 - Tutorials
3-15
References
Socket Programming, Dan Rubinstein,
http://www1.cs.columbia.edu/~danr/courses/6761/Fall00/intro/6761-1bsockets.ppt
 15-441 Socket Programming, www.cs.cmu.edu/afs/cs/academic/class/15441f01/www/lectures/lecture03.ppt
 Network Programming, Geoff Kuenning,
www.cs.hmc.edu/~geoff/classes/hmc.cs105.200701/slides/class21_net2.ppt
