socket-programming. establish contact (connection). exchange information (bi-directional). ...
TRANSCRIPT
Socket-Programming
BASIC PARADIGM FOR COMMUNICATION
Establish contact (connection). Exchange information (bi-directional). Terminate contact.
3
Network
Reque
st
Result
a client, a server, and network
ClientServer
Client machineServer machine
ELEMENTS OF C-S COMPUTING
CLIENT/SERVER COMPUTING
Other examples: Chatroom
TWO TYPES OF COMMUNICATION
Connection-oriented Setup the link before communication. Similar to the phone call. We need the
phone number and receiver. Connectionless
No link needed to be set up before communication.
Similar to send a letter. We need the address and receiver.
6
NETWORKING BASICS
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival.
Example applications: Clock server Ping
TCP/IP Stack
Application(http,ftp,telnet,…)
Transport(TCP, UDP,..)
Network(IP,..)
Link(device driver,..)
7
UNDERSTANDING PORTS
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
server
PORT
ClientTCP
TCP or UDP
port port port port
app app app app
port# dataData
Packet
SOCKETS
Figure 2.6-2: Client socket, welcoming socket and connection socket
CLIENT-SERVER PARADIGM
Server waits for client to request a connection.
Client contacts server to establish a connection.
Client sends request. Server sends reply. Client and/or server terminate
connection.
WHAT IS A SOCKET?
Socket The combination of an IP address and a port number. (RFC
793 ,original TCP specification) The name of the Berkeley-derived application programming
interfaces (APIs) for applications using TCP/IP protocols. Two types
Stream socket : reliable two-way connected communication streams Datagram socket
Socket pair Specified the two end points that uniquely identifies each TCP
connection in an internet. 4-tuple: (client IP address, client port number, server IP address,
server port number)
PORTS Some “well-known” ports:
21: ftp 23: telnet 80: http 161: snmp
Check out /etc/services file for complete list of ports and services associated to those ports
Port numbers between 0 .. 1023 are reserved User level process/services generally use
port number value >= 1024
SOCKET PROGRAMMING WITH UDP
UDP Connectionless and unreliable service. There isn’t an initial handshaking phase. Doesn’t have a pipe. transmitted data may be received out of order, or lost
Socket Programming with UDP No need for a welcoming socket. No streams are attached to the sockets. the sending hosts creates “packets” by attaching the IP destination
address and port number to each batch of bytes. The receiving process must unravel to received packet to obtain
the packet’s information bytes.
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
SOCKET PROGRAMMING - FLOW
socket()
connect()
send()
recv()
close()
..
.
socket()
bind()
listen()
accept()
recv()
send()
close()
wait for connection request from next client
Client Server
UDP PROTOCOL
JAVA SOCKETS PROGRAMMING
The package java.net provides support for sockets programming (and more).
Typically you import everything defined in this package with:
import java.net.*;
Java Socket Programming
16
JAVA API FOR UDP DATAGRAMS
The Java API provides datagram communication by means of two classes: DatagramPacket - Datagram packets are used
to implement a connectionless packet delivery service.
DatagramSocket - A datagram socket is the sending or receiving point for a packet delivery service.
DatagramPacket: getData - Returns the data buffer. getPort - Returns the port number on the
remote host. getAddress - Returns the IP address.
JAVA API FOR UDP DATAGRAMS
DatagramSocket: send - Sends a datagram packet from this
socket. receive - Receives a datagram packet
from this socket. setSoTimeout - Enable/disable the
specified timeout, in milliseconds. connect - Connects the socket to a
remote address for this socket.
CLASSES
InetAddress
Socket
ServerSocket
DatagramSocket
DatagramPacket
Java Socket Programming
19
UDP SOCKETS
DatagramSocket class
DatagramPacket class needed to specify the payload incoming or outgoing
Java Socket Programming
20
JAVA UDP SOCKETS
In Package java.net java.net.DatagramSocket
A socket for sending and receiving datagram packets.
Constructor and Methods DatagramSocket(int port): Constructs a datagram
socket and binds it to the specified port on the local host machine.
void receive( DatagramPacket p) void send( DatagramPacket p) void close()
Java Socket Programming
21
DATAGRAMSOCKET CONSTRUCTORS
DatagramSocket();
DatagramSocket(int port);
DatagramSocket(int port, InetAddress a);
All can throw SocketException or SecurityException
Java Socket Programming
22
DATAGRAM METHODS
void connect(InetAddress, int port);
void close();
void receive(DatagramPacket p);
void send(DatagramPacket p);
Java Socket Programming
23
DATAGRAM PACKET
Contain the payload (a byte array
Can also be used to specify the destination address when not using connected mode UDP
Java Socket Programming
24
DATAGRAMPACKET CONSTRUCTORS
For receiving:
DatagramPacket( byte[] buf, int len);
For sending:
DatagramPacket( byte[] buf, int len InetAddress a, int port);
Java Socket Programming
25
SOCKET CLASS
Corresponds to active TCP sockets only! client sockets socket returned by accept();
Passive sockets are supported by a different class: ServerSocket
UDP sockets are supported by DatagramSocket
Java Socket Programming
26
CPSC 441 - Application Layer
27ou
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 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.
CLIENT/SERVER SOCKET INTERACTION: UDP
closeclientSocket
Server (running on hostid)
read reply fromclientSocket
create socket,clientSocket = DatagramSocket()
Client
Create, address (hostid, port=x,send datagram request using clientSocket
create socket,port=x, forincoming request:serverSocket = DatagramSocket()
read request fromserverSocket
write reply toserverSocketspecifying clienthost address,port umber
CPSC 441 - Application Layer
29
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
30
SOCKET COMMUNICATION
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request.
serverClient
Connection requestport
31
SOCKET COMMUNICATION
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client.
server
ClientConnection
port
port port
SOCKET FUNCTIONAL CALLS
socket (): Create a socket bind(): bind a socket to a local IP address and port # listen(): passively waiting for connections connect(): initiating connection to another socket accept(): accept a new connection Write(): write data to a socket Read(): read data from a socket sendto(): send a datagram to another UDP socket recvfrom(): read a datagram from a UDP socket close(): close a socket (tear down the connection)
JAVA UDP SOCKETS
In Package java.net java.net.DatagramSocket
A socket for sending and receiving datagram packets.
Constructor and Methods DatagramSocket(int port): Constructs a datagram
socket and binds it to the specified port on the local host machine.
void receive( DatagramPacket p) void send( DatagramPacket p) void close()
UDPCLIENT.JAVA
import java.io.*; import java.net.*;
class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
UDPCLIENT.JAVA
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close(); } }
UDPSERVER.JAVAimport java.io.*; import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData());
UDPSERVER.JAVA
InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket);
} }}
38
IMPLEMENTING A SERVER1. Open the Server Socket:
ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT );2. Wait for the Client Request:
Socket client = server.accept();3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() );4. Perform communication with client Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");5. Close sockets: client.close();For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3)
and does communication as stated in (4). Remove thread once service is provided.}
39
IMPLEMENTING A CLIENT
1. Create a Socket Object:client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server: Receive data from the server:
String line = is.readLine(); Send data to the server:
os.writeBytes("Hello\n");4. Close the socket when done: client.close();
40
A SIMPLE SERVER (SIMPLIFIED CODE) // SimpleServer.java: a simple server programimport java.net.*;import java.io.*;public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); }}
41
A SIMPLE CLIENT (SIMPLIFIED CODE)
// SimpleClient.java: a simple client programimport java.net.*;import java.io.*;public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); }}
42
RUN Run Server on mundroo.cs.mu.oz.au
[raj@mundroo] java SimpleServer &
Run Client on any machine (including mundroo): [raj@mundroo] java SimpleClient
Hi there
If you run client when server is not up: [raj@mundroo] sockets [1:147] java SimpleClientException in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120) at java.net.Socket.<init>(Socket.java:273) at java.net.Socket.<init>(Socket.java:100) at SimpleClient.main(SimpleClient.java:6)
43
SOCKETS AND JAVA SOCKET CLASSES A socket is an endpoint of a two-way
communication link between two programs running on the network.
A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent.
Java’s .net package provides two classes: Socket – for implementing a client ServerSocket – for implementing a server
44
IMPLEMENTING A SERVER1. Open the Server Socket:
ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT );2. Wait for the Client Request:
Socket client = server.accept();3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() );4. Perform communication with client Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");5. Close sockets: client.close();For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “client” socket as parameter (the thread creates streams (as in step (3)
and does communication as stated in (4). Remove thread once service is provided.}
45
IMPLEMENTING A CLIENT
1. Create a Socket Object:client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server: Receive data from the server:
String line = is.readLine(); Send data to the server:
os.writeBytes("Hello\n");4. Close the socket when done: client.close();
46
A SIMPLE SERVER (SIMPLIFIED CODE) // SimpleServer.java: a simple server programimport java.net.*;import java.io.*;public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); }}
47
A SIMPLE CLIENT (SIMPLIFIED CODE)
// SimpleClient.java: a simple client programimport java.net.*;import java.io.*;public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); }}
48
RUN Run Server on mundroo.cs.mu.oz.au
[raj@mundroo] java SimpleServer &
Run Client on any machine (including mundroo): [raj@mundroo] java SimpleClient
Hi there
If you run client when server is not up: [raj@mundroo] sockets [1:147] java SimpleClientException in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120) at java.net.Socket.<init>(Socket.java:273) at java.net.Socket.<init>(Socket.java:100) at SimpleClient.main(SimpleClient.java:6)
49
NETWORKING BASICS
TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers.
Example applications: HTTP FTP Telnet
TCP/IP Stack
Application(http,ftp,telnet,…)
Transport(TCP, UDP,..)
Network(IP,..)
Link(device driver,..)