Socket-Programming. Establish contact (connection). Exchange information (bi-directional). ...

49
Socket- Programming

Transcript of Socket-Programming. Establish contact (connection). Exchange information (bi-directional). ...

Page 1: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

Socket-Programming

Page 2: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

BASIC PARADIGM FOR COMMUNICATION

Establish contact (connection). Exchange information (bi-directional). Terminate contact.

Page 3: Socket-Programming.  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

Page 4: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

CLIENT/SERVER COMPUTING

Other examples: Chatroom

Page 5: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 6: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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,..)

Page 7: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 8: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

SOCKETS

Figure 2.6-2: Client socket, welcoming socket and connection socket

Page 9: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 10: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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)

Page 11: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 12: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 13: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 14: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

SOCKET PROGRAMMING - FLOW

socket()

connect()

send()

recv()

close()

..

.

socket()

bind()

listen()

accept()

recv()

send()

close()

wait for connection request from next client

Client Server

Page 15: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

UDP PROTOCOL

Page 16: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 17: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 18: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 19: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

CLASSES

InetAddress

Socket

ServerSocket

DatagramSocket

DatagramPacket

Java Socket Programming

19

Page 20: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

UDP SOCKETS

DatagramSocket class

DatagramPacket class needed to specify the payload incoming or outgoing

Java Socket Programming

20

Page 21: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 22: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

DATAGRAMSOCKET CONSTRUCTORS

DatagramSocket();

DatagramSocket(int port);

DatagramSocket(int port, InetAddress a);

All can throw SocketException or SecurityException

Java Socket Programming

22

Page 23: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

DATAGRAM METHODS

void connect(InetAddress, int port);

void close();

void receive(DatagramPacket p);

void send(DatagramPacket p);

Java Socket Programming

23

Page 24: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 25: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

DATAGRAMPACKET CONSTRUCTORS

For receiving:

DatagramPacket( byte[] buf, int len);

For sending:

DatagramPacket( byte[] buf, int len InetAddress a, int port);

Java Socket Programming

25

Page 26: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 27: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.

Page 28: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 29: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 30: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 31: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 32: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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)

Page 33: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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()

Page 34: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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();

Page 35: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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();       } }

Page 36: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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());

Page 37: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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);

      } }}

Page 38: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.}

Page 39: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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();

Page 40: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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(); }}

Page 41: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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(); }}

Page 42: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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)

Page 43: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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

Page 44: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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.}

Page 45: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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();

Page 46: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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(); }}

Page 47: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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(); }}

Page 48: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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)

Page 49: Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.

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,..)