Sie sind auf Seite 1von 16

Socket programming

Goal: learn how to build client/server application that


communicate using sockets
Socket API socket
• introduced in BSD4.1 UNIX, 1981
a host-local, application-
• explicitly created, used, released by
apps created/owned,
OS-controlled interface
• client/server paradigm
(a “door”) into which
• two types of transport service via application process can
socket API:
both send and
– unreliable datagram receive messages to/from
– reliable, byte stream-oriented another (remote or
local) application process
Socket-programming using TCP
Socket: a door between application process and end-end-
transport protocol (UDP or TCP)
TCP service: reliable transfer of bytes from one process to
another

controlled by
controlled by process application
application process
developer
developer socket socket
TCP with TCP with controlled by
controlled by
buffers, operating
operating buffers, internet system
system variables variables

host or host or
server server
Socket programming with TCP
Client must contact server • When client creates socket:
• server process must first client TCP establishes
be running connection to server TCP
• When contacted by client,
• server must have created
server TCP creates new
socket (door) that socket for server process to
welcomes client’s contact communicate with client
Client contacts server by: – allows server to talk with
• creating client-local TCP multiple clients
socket
• specifying IP address, port
number of server process
application viewpoint
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server
Socket programming with TCP
Example client-server app: k e y b o a rd m o n ito r

• client reads line from standard


input (inFromUser stream) ,

inFromUser
in p u t
sends to server via socket s tr e a m

(outToServer stream) Client


P ro c e s s Input stream:
• server reads line from socket process sequence of bytes
output stream: into process
• Example: server converts
sequence of bytes
alphabets received from client
out of process
to uppercase, sends back to

inFromServer
outToServer
o u tp u t in p u t
client s t r e a m s tr e a m

• client reads, prints modified line


client TCP
from socket (inFromServer c lie n t S o c k e t
socket TC P
stream) socket

to n e tw o r k fr o m n e tw o r k
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
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 BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream());
attached to socket
Example: Java client (TCP), cont.

Create BufferedReader inFromServer =


input stream new BufferedReader(new
attached to socket InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();
Send line
to server outToServer.writeBytes(sentence + '\n');

Read line modifiedSentence = inFromServer.readLine();


from server
System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close();

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

class TCPServer {

public static void main(String argv[]) throws Exception


{
String clientSentence;
Create String capitalizedSentence;
welcoming socket
ServerSocket welcomeSocket = new ServerSocket(6789);
at port 6789
while(true) {
Wait, on welcoming
socket for contact Socket connectionSocket = welcomeSocket.accept();
by client
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(connectionSocket.getInputStream()));
to socket
Example: Java server (TCP), cont
Create output
stream, attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine();

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


Write out line
outToClient.writeBytes(capitalizedSentence);
to socket
}
}
} End of while loop,
loop back and wait for
another client connection
Socket programming with UDP
UDP: no “connection” between
client and server
• no handshaking
• sender explicitly attaches IP application viewpoint
address and port of UDP provides unreliable transfer
destination of groups of bytes (“datagrams”)
• server must extract IP between client and server
address, port of sender from
received datagram
UDP: transmitted data may be
received out of order, or lost
Client/server socket interaction: UDP
Server (running on hostid) Client

create socket,
port=x, for create socket,
clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket

write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket
Example: Java client (UDP)
k e y b o a rd m o n ito r

inFromUser
in p u t
s tr e a m

PClient
ro c e s s
Input: receives
process
packet (TCP
Output: sends received “byte
packet (TCP sent stream”)

receivePacket
sendPacket
“byte stream”) UD P U D P
packet packet

client
c l i e n t S o c UDP
ket
socket UDP
socket

to n e tw o r k fr o m n e tw o r k
Example: Java client (UDP)
import java.io.*;
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket DatagramSocket clientSocket = new DatagramSocket();
Translate
InetAddress IPAddress = InetAddress.getByName("hostname");
hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();
Example: Java client (UDP), cont.
Create datagram
with data-to-send, DatagramPacket sendPacket =
length, IP addr, port new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

Send datagram clientSocket.send(sendPacket);


to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Read datagram
clientSocket.receive(receivePacket);
from server
String modifiedSentence =
new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);


clientSocket.close();
}
}
Example: Java server (UDP)
import java.io.*;
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];

while(true)
{
Create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
InetAddress IPAddress = receivePacket.getAddress();
port #, of
sender int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram