316x Filetype PDF File size 0.36 MB Source: www.cs.cornell.edu
Socket Programming Socket programming
Goal: learn how to build client/server application
that communicate using sockets
Socket API socket
Rohan Murty introduced in BSD4.1 a host-local, application-
UNIX, 1981 created/owned,
Hitesh Ballani Sockets are explicitly OS-controlled interface (a
created, used, released by “door”) into which
applications application process can
Last Modified: client/server paradigm both send and
two types of transport receive messages to/from
2/8/2004 8:30:45 AM another (remote or
service via socket API: local) application process
– unreliable datagram
Slides adapted from Prof. Matthews’ slides from 2003SP – reliable, byte stream-
oriented
Sockets Languages and Platforms
Socket: a door between application Socket API is available for many languages
process and end-end-transport protocol on many platforms:
(UCP or TCP) C, Java, Perl, Python,…
*nix, Windows,…
controlled by controlled by
application process process application
developer socket socket developer Socket Programs written in any language
controlled by kernel kernel controlled by
operating buffers, internet buffers, operating and running on any platform can
system variables variables system communicate with each other!
host or host or Writing communicating programs in different
server server languages is a good exercise
1
Decisions Socket programming with TCP
Client must contact server When client creates socket:
Before you go to write socket code, decide server process must client TCP establishes
first be running connection to server TCP
–Do you want a TCP-style reliable, full duplex, When contacted by client,
connection oriented channel? Or do you want server must have server TCP creates new
created socket (door) socket for server process to
a UDP-style, unreliable, message oriented that welcomes client’s communicate with client
channel? – Frees up incoming port
contact – allows server to talk with
–Will the code you are writing be the client or Client contacts server by: multiple clients
the server? creating client-local application viewpoint
Client: you assume that there is a process already TCP socket TCP provides reliable, in-order
running on another machines that you need to specifying IP address, transfer of bytes (“pipe”)
connect to. port number of server between client and server
Server: you will just start up and wait to be process
contacted
Pseudo code TCP client Pseudo code TCP server
Create socket, connectSocket Create socket (serverSocket)
Do an active connect specifying the IP Bind socket to a specific port where clients can contact
you
address and port number of server Register with the kernel your willingness to listen that on
Read and Write Data Into socket for client to contact you
Loop
connectSocket to Communicate with Accept new connection (connectSocket)
server Read and Write Data Into connectSocket to
Close connectSocket Communicate with client
Close connectSocket
End Loop
Close serverSocket
2
Example: Java client (TCP) Example: Java client (TCP), cont.
import java.io.*;
import java.net.*; Create BufferedReader inFromServer =
class TCPClient { input stream new BufferedReader(new
public static void main(String argv[]) throws Exception attached to socket InputStreamReader(clientSocket.getInputStream()));
{ sentence = inFromUser.readLine();
String sentence; Send line
String modifiedSentence; to server outToServer.writeBytes(sentence + '\n');
Create BufferedReader inFromUser =
input stream new BufferedReader(new InputStreamReader(System.in)); Read line modifiedSentence = inFromServer.readLine();
Create from server
client socket, Socket clientSocket = new Socket("hostname", 6789); System.out.println("FROM SERVER: " + modifiedSentence);
connect to server clientSocket.close();
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream()); }
attached to socket }
Example: Java server (TCP) Example: Java server (TCP), cont
import java.io.*;
import java.net.*;
Create output
class TCPServer { stream, attached DataOutputStream outToClient =
public static void main(String argv[]) throws Exception to socket new DataOutputStream(connectionSocket.getOutputStream());
{ Read in line
String clientSentence; from socket clientSentence = inFromClient.readLine();
Create String capitalizedSentence;
welcoming socket ServerSocket welcomeSocket = new ServerSocket(6789); capitalizedSentence = clientSentence.toUpperCase() + '\n';
at port 6789 Write out line
while(true) { to socket outToClient.writeBytes(capitalizedSentence);
Wait, on welcoming }
socket for contact Socket connectionSocket = welcomeSocket.accept(); }
by client } End of while loop,
Create input BufferedReader inFromClient = loop back and wait for
stream, attached new BufferedReader(new another client connection
to socket InputStreamReader(connectionSocket.getInputStream()));
3
Client/server socket interaction: TCP Queues
(Java)
Server (running on hostid) Client We just saw a simple example, with one socket on the
create socket, server handling incoming connections
port=x, for
incoming request: While the server socket is busy, incoming connections
welcomeSocket=
ServerSocket() are stored in a queue until it can accept them
wait for incoming TCP create socket, Most systems maintain a queue length between 5 and
connection request connection setup connect to hostid, port=x 50
connectionSocket = clientSocket =
welcomeSocket.accept() Socket() Once the queue fills up, further incoming connections
send request using are refused until space in the queue opens up
read request from clientSocket This is a problem in a situation where our server has to
connectionSocket handle many concurrent incoming connections.
write reply to Example: HTTP servers
connectionSocket read reply from
clientSocket – Solution? Use concurrency
close close
connectionSocket clientSocket
Concurrent TCP Servers Threadpools
Benefit comes in ability to hand off processing to another
process 1
– Parent process creates the “door bell” or “welcome” serverSocket Client
socket on well-known port and waits for clients to
request connection 2 2.1
– When a client does connect, fork off a child process to
handle that connection so that parent process can Thread 3
return to waiting for connections as soon as possible Pool
Multithreaded server: same idea, just spawn off another
thread rather than a full process Worker Threads Client
– Threadpools?
4
no reviews yet
Please Login to review.