• No se han encontrado resultados

Tema 1. Comunicación entre Procesos, Sockets

N/A
N/A
Protected

Academic year: 2021

Share "Tema 1. Comunicación entre Procesos, Sockets"

Copied!
9
0
0

Texto completo

(1)

1

Tema 1

2

Comunicación entre

Procesos,

Sockets

Objetivos



Conceptos Básicos: sincronización IPC,

direcciones y puertos, Paradigmas IPC.



IPC sin conexión: Sockets Datagrama.



IPC orientada conexión: Sockets Stream.

IPC Sistema Distribuido vs.

Sistema Operativo.

-

La computación distribuida require intercambio de

información entre procesos independientes.

-

Los sistemas operativos proveen mecanismos para la

comunicación entre procesos (IPC), como señales,

tuberias, colas de mensajes, streams, semaforos y

memoria compartida.

-

Para los sistemas distribuidos se intentan diseñar

mecanismos que provean el mismo Interface de

Programación de Aplicaciones (API):

-

Transparencia de localización: (enviar mensaje local = enviar

mensaje remoto)

(2)

5

Sincronización en IPC



IPC require la sincronización de las operaciones de los

dos procesos: una parte envia, entonces la otra parte

recibe hasta que todos los datos hayan sido enviados y

recibidos.



Idealmente, la operación enviar comienzo antes que la

operación recibir.

Receive()

interprocess communication

execution flow

IPC Ideal

time

Receive()

Send()

Process A

Process B

mensaje 1

Send()

6

Envio asincrono (no-bloqueante)

recepción sincrona (bloqueante)

Receive()

interprocess communication

execution flow

process blocked

Eventos en IPC paso de mensajes

time

Receive() bloking

Send()

Process A

Process B

request 1

Send() non-bloking



Las operaciones IPC proveen la sincronización necesaria

utilizando

bloqueo

:

Una operación bloqueante bloqueara su proceso

hasta que haya finalizado.



Las operaciones IPC tambien pueden ser asincronas o

nobloqueantes

.

Una

operación

asincrona

no

bloqueara

el

procesamiento de más instrucciones del proceso. El proceso es libre de

seguir procesando, y puede opcionalmente ser notificado por el sistema

cuando la operación haya finalizado.

Deadlocks y timeouts



Operaciones bloqueantes efectuadas en un orden incorrecto

pueden pueden causar deadlocks.(abrazo mortal).



Los deadlocks deben de ser evitados.



No es aceptable que un proceso espere indefinidamente. Los

bloqueos indefinidos se evitan usando

timeout

.

receive from process 2 issued

received from process 1 issued

process 1 blocked pending data

from process 2.

process 2 blocked pending data

from process 1.

Process 1

Process 2

Receive()

Receive()

SetTimeout(3)

Timeout()

Direcciones y Puertos



Destino de mensajes se define por:



una dirección IP (o un nombre DNS) y un puerto.



Un puerto es un destino en un ordenador. Cada ordenador tiene

multiples puertos: 2

16

(65,535).



Los puertos numerados entre el 1 y 1023 estan reservados para

procesos que proveen servicios conocidos: finger, FTP, HTTP, and

email.



Cada proceso puede enviar y recibir por multiples puertos.

message

agreed port

any port

Internet address = 138.37.88.249

Internet address = 138.37.94.248

other ports

Proc1

Proc1

Proc2

Proc7

(3)

9

Paradigmas IPC

Hay diferentes mecanismos de IPC con diferentes niveles

de abstracción.

Los mecanismos de IPC se construyen unos sobre otros.

Los mecanismos superiores simplifican la programación de

las aplicaciones.

remote procedure/method

socket

Datagramas

Sockets

RMI

level of

abstraction

IPC paradigms

Example IPC Implementations

Cliente- Servidor

Paso mensajes

10

Process 1

Process 2

data

sender

receiver

Paso de Mensajes

• Paradigma IPC más sencillo.

•Sobre él se construyen otros IPC.

•(Implementaciones: Paquetes IP, Datagramas.)

Primitivas:

•SEND([receiver],message)

•RECEIVE([sender],

message storage object).

Datagramas: emisor

import java.net.*; import java.io.*;

public class Example1Sender { public static void main(String[] args) {

if (args.length != 3)

System.out.println ("This program requires three command line arguments"); else {

try {

InetAddress receiverHost = InetAddress.getByName(args[0]); int receiverPort = Integer.parseInt(args[1]);

String message = args[2];

// instantiates a datagram socket for sending the data DatagramSocket mySocket = new DatagramSocket(); byte[ ] buffer = message.getBytes( ); DatagramPacket datagram =

new DatagramPacket(buffer, buffer.length, receiverHost, receiverPort); mySocket.send(datagram);

mySocket.close( ); } // end try

catch (Exception ex) { ex.printStackTrace( ); } } // end else } // end main } // end class

receptor

emisor

datagram

DataGramSocket.send()

DataGramSocket.receive()

import java.net.*; import java.io.*;

public class Example1Receiver { public static void main(String[] args) {

if (args.length != 1) System.out.println ("This program requires a command line argument."); else {

int port = Integer.parseInt(args[0]);

final int MAX_LEN = 10; // This is the assumed maximum byte length try { // instantiates a datagram socket for receiving the data DatagramSocket mySocket = new DatagramSocket(port); byte[ ] buffer = new byte[MAX_LEN]; DatagramPacket datagram =

new DatagramPacket(buffer, MAX_LEN); mySocket.receive(datagram);

String message = new String(buffer); System.out.println(message); mySocket.close( ); } // end try

catch (Exception ex) { ex.printStackTrace( );} } // end else } // end main } // end class

Datagramas: receptor

receptor

emisor

datagram

DataGramSocket.send()

DataGramSocket.receive()

(4)

13

Envio-Recepción varios datagramas.

import java.net.*; import java.io.*;

public class Example1Sender { public static void main(String[] args) { try {

InetAddress receiverHost = InetAddress.getByName(args[0]); int receiverPort = Integer.parseInt(args[1]);

String message = args[2];

// instantiates a datagram socket for sending the data DatagramSocket mySocket = new DatagramSocket(); byte[ ] buffer = message.getBytes( ); DatagramPacket datagram =

new DatagramPacket(buffer, buffer.length, receiverHost, receiverPort); mySocket.send(datagram); mySocket.send(datagram); mySocket.send(datagram); mySocket.send(datagram); mySocket.close( ); } // end try

catch (Exception ex) { ex.printStackTrace( ); } } // end else } // end main } // end class

¿¿Receptor??

emisor

datagram

DataGramSocket.send()

datagram

DataGramSocket.send()

datagram

DataGramSocket.send()

datagram

DataGramSocket.send()

14

Transmisión con Datagramas

server

client

data1 blocked

DataGramSocket.send()

DataGramSocket.receive()

blocking receive,

nonblocking send

if data is sent before a corresponding receive operation is issued, the data will

be discarded by the runtime support and will not be received.

data3 data2 data4

DataGramSocket.send()

DataGramSocket.send()

DataGramSocket.send()

Recibido:

Data1

Data 3

Data 2

Enviado:

Data1

Data 2

Data 3

Data 4

DataGramSocket.receive()

DataGramSocket.receive()

DataGramSocket.receive()

Socket Datagrama en JAVA

Method/Constructor Description

DatagramPacket(byte[ ] buf, int length)

Construct a datagram packet for receiving packets of length length; data received will be stored in the byte array reference by buf.

DatagramPacket(byte[ ] buf, int length, InetAddress address, int port)

Construct a datagram packet for sending packets of length length to the socket bound to the specified port number on the specified host; data received will be stored in the byte array reference by buf.

DatagramSocket( )

Construct a datagram socket and binds it to any available port on the local host machine; this constructor can be used for a process that sends data and does not need to receive data.

DatagramSocket(int port) Construct a datagram socket and binds it to the specified port on the local host machine; the port number can then be specified in a datagram packet sent by a sender.

void close( ) Close this datagramSocket object

void receive(DatagramPacket p)

Receive a datagram packet using this socket.

void send (DatagramPacket p) Send a datagram packet using this socket.

void setSoTimeout(int timeout)

Set a timeout for the blocking receive from this socket, in milliseconds.

IPC sin / con conexión

Process A

socket

API runtime support

Process B

API runtime

socket

support

transport layer software

transport layer software

a datagram

a logical connection created and maintained

by the runtime support of the datagram

socket API

Process A

socket

API runtime support

Process B

API runtime

socket

support

transport layer software

transport layer software

connectionless datagram socket

(5)

17

Socket con conexión: Stream-mode

Socket API

...

...

a data stream

process write operation read operation P1 P2

a stream-mode data socket

Los Stream Sockets:

•no descartan mensajes,

•Entregan al proceso los datos ordenados.

•Se puede leer y escribir en un mismo socket

(con 2 stream, como en el SO)

18

Establecimiento Conexión

1. Servidor crea

socket de conexión

y se pone a la

escucha de

conexión:

2. Un cliente

crea un socket

con la dirección

del servidor

remoto.

Listener

Requester

3. El servidor

accepta la conexión

y crea un nuevo

socket de datos.

Connection

socket

Connection

socket

Data socket

Cada servidor utilizan dos sockets para establecer conexiones.

4. El cliente es

informado del puerto

del data socket.

19

Envio/Recepción Datos

Connection

socket

Connection

socket

Connection

socket

Data socket

Data socket

5. El servidor realiza

una operación

“receive” en el

socket de datos.

7. El servidor

responde por el

socket de datos.

9. Cuando acaba el

protocolo, el servidor

cierra el socket de

datos. El socket de

conexión puede

seguir recibiendo

conexiones.

6. El cliente realiza

una operación

“send”. Y el cliente

realiza un “receive”.

8. Recibe los datos

del servidor.

10. El cliente cierra

su socket cuando el

protocolo ha

completado .

5,6,7,8 podrian ser al revés, servidor envia y cliente recibe (ver ejemplo

Example4ConnectionAcceptor y Example4ConnectionRequestor)

20

Flujo de programas conectado por

Sockets en modo stream

connection listener (server)

create a connection socket and listen for connection requests;

accept a connection;

creates a data socket for reading from or writing to the socket stream; get an input stream for reading to the socket;

read from the stream; get an output stream for writing to the socket;

write to the stream; close the data socket; close the connection socket.

connection requester (client)

create a data socket and request for a connection; get an output stream for writing to the socket;

write to the stream; get an input stream for reading to the socket;

read from the stream; close the data socket.

(6)

21

The Stream-mode Socket API



El API de sockets datagramas solo soporta el

intercambio de unidades sencillas de datos, los

datagramas.



El API

stream socket

provee

un modo

de

transferencia basado en los streams de I/O del

sistema operativo Unix:



1 socket en cada extremo con 2 streams: out e in.



Por definición, un socket en modo streams soporta

solo comunicaciones con conexión.



Un socket stream se establece entre dos procesos

especificos.



Un socket stream no puede utilizarse para comunicar con

más de un proceso (hay que utilizar varios sockets).

22 import java.net.*;

import java.io.*;

public class Example4ConnectionAcceptor { public static void main(String[] args) {

if (args.length != 2) System.out.println ("This program requires two command line arguments"); else {

try { int portNo = Integer.parseInt(args[0]);

String message = args[1]; // instantiates a socket for accepting connection ServerSocket connectionSocket = new ServerSocket(portNo); /**/ System.out.println("Now ready to accept a connection");

// wait to accept a connecion request, at which time a data socket is created Socket dataSocket = connectionSocket.accept();

/**/ System.out.println("connection accepted"); // get a output stream for writing to the data socket OutputStream outStream = dataSocket.getOutputStream(); // create a PrinterWriter object for character-mode output

PrintWriter socketOutput = new PrintWriter(new OutputStreamWriter(outStream)); // write a message into the data stream

socketOutput.println(message);

//The ensuing flush method call is necessary for // the data to be written to the socket data //stream before the socket is closed. socketOutput.flush();

/**/ System.out.println("message sent"); dataSocket.close( );

/**/ System.out.println("data socket closed"); connectionSocket.close( );

/**/ System.out.println("connection socket closed"); } // end try

catch (Exception ex) { ex.printStackTrace( ); } //end catch } // end else } // end main } // end class

connect

accept write close data socket close

connection socket connect request (from Socket constructor)

read ConnectionAcceptor ConnectionRequestor close socket

message

23 import java.net.*; import java.io.*;

public class Example4ConnectionRequestor { public static void main(String[] args) {

if (args.length != 2) System.out.println ("This program requires two command line arguments"); else {

try { InetAddress acceptorHost = InetAddress.getByName(args[0]); int acceptorPort = Integer.parseInt(args[1]);

// instantiates a data socket

Socket mySocket = new Socket(acceptorHost, acceptorPort); /**/ System.out.println("Connection request granted");

// get an input stream for reading from the data socket InputStream inStream = mySocket.getInputStream(); // create a BufferedReader object for text line input

BufferedReader socketInput = new BufferedReader(new InputStreamReader(inStream)); /**/ System.out.println("waiting to read");

// read a line from the data stream String message = socketInput.readLine( ); /**/ System.out.println("Message received:");

System.out.println("\t" + message); mySocket.close( );

/**/ System.out.println("data socket closed"); } // end try

catch (Exception ex) { ex.printStackTrace( ); } //end catch } // end else } // end main } // end class

connect

accept write close data socket close

connection socket connect request (from Socket constructor)

read

ConnectionAcceptor ConnectionRequestor

message

24

JAVA Stream Socket API (I)

M e th o d /c o n stru c to r

D e sc rip tio n

S e rve rS o c k e t(in t p o rt)

C re a te s a se rve r so c k e t o n a sp e c ifie d p o rt.

S o c k e t a c c e p t()

th ro w s

IO E x c e p tio n

Liste n s fo r a c o n n e c tio n to b e m a d e to th is so c k e t a n d

a c c e p ts it. T h e m e th o d b lo c k s u n til a c o n n e c tio n is m a d e .

p u b lic vo id c lo se ()

th ro w s IO E x c e p tio n

C lo se s th is so c k e t.

vo id

se tS o T im e o u t(in t tim e o u t)

th ro w s

S o c k e tE x c e p tio n

S e t a tim e o u t p e rio d (in m illise c o n d s) so th a t a c a ll to

a c c e p t( ) fo r th is so c k e t w ill b lo c k fo r o n ly th is a m o u n t o f

tim e . If th e tim e o u t e x p ire s, a

ja va .io .In te rru p te d IO E x c e p tio n is ra ise d

Note:

Accept is a blocking operation

.

Java provee dos clases para sockets en modo stream:



Server socket

:para aceptar conexiones (conexion socket)



Socket

: para intercambiar datos (Data socket) for data exchange;

we will call an object of this class a data socket.

(7)

25

JAVA Stream Socket API (II)

Method/constructor

Description

Socket

(

InetAddress

address,

int port)

Creates a stream socket and connects it to the

specified port number at the specified IP address

void close()

throws

IOException

Closes this socket.

InputStream

getInputStream( )

throws

IOException

Returns an input stream so that data may be read

from this socket.

OutputStream

getOutputStream(

)throws

IOException

Returns an output stream so that data may be written

to this socket.

void setSoTimeout(int timeout)

throws

SocketException

Set a timeout period for blocking so that a read( ) call

on the InputStream associated with this Socket will

block for only this amount of time. If the timeout

expires, a java.io.InterruptedIOException is raised

A read operation on the InputStream is blocking.

A write operation is nonblocking.

Metodos de Socket:

26

Protocolo HTTP

Protocolos

-

En un sistema distribuido, dos o más procesos

establecen

comunicación

IPC en un protocolo

acordado por los procesos. Un proceso será emisor

en algunos instantes del protocolo, y receptor en

otros momentos.



Las especificaciones de un protocolo deben incluir:



(i) la sequencia del intercambio de datos, que se puede

describir usando un diagrama de eventos en el tiempo.



(ii) las especificaciones del formato de datos

intercambiado en cada paso.

Protocolo HTTP

Web Server

Web Client

DIAGRAMA DE EVENTOS

Request

Response

time

Request:

“METODO URL VERSION”

Metodo=GET|POST|PUT

…………

Response:

“STATUS HEADERS BODY”

STATUS=100|101|….

…….

……

FORMATO DE DATOS

•Protocolo de nivel aplicación sobre stream sockets.

•Datos en formato texto.

(8)

29

A sample HTTP session (telnet version)

$ telnet www.csc.calpoly.edu 80

Trying 129.65.241.20...

Connected to tiedye2-srv.csc.calpoly.edu.

Escape character is '^]'.

GET /index.html HTTP/1.0

HTTP/1.1 200 OK

Date: Wed, 11 Oct 2000 04:51:18 GMT

Server: Apache/1.3.9 (Unix) ApacheJServ/1.0

Last-Modified: Tue, 10 Oct 2000 16:51:54 GMT

ETag: "1dd1e-e27-39e3492a"

Accept-Ranges: bytes

Content-Length: 3623

Connection: close

Content-Type: text/html

<HTML>

<HEAD>

<TITLE> Mei-Ling L. Liu's Home Page

</TITLE>

</HEAD>

<BODY bgcolor=#ffffff>

Server host

Web Client: Iexplorer, FireFox, Telnet,….

GET /index.html HTTP/1.0

HTTP/1.1 200 OK Date: Wed, 11 Oct 2000 04:51:18

GMT Server: Apache/1.3.9 (Unix) ApacheJServ/1.0

Last-Modified: Tue, 10 Oct 2000 16:51:54 GMT ETag: "1dd1e-e27-39e3492a" Accept-Ranges: bytes Content-Length: 3623 Connection: close Content-Type: text/html <HTML> <HEAD>

<TITLE> Mei-Ling L. Liu's Home Page </TITLE> </HEAD> <BODY bgcolor=#ffffff> 30 import java.net.*; import java.io.*; public class HTTPClient {

public static void main(String[] args) { if (args.length != 3)

System.out.println

("This program requires 3 command line arguments"); else {

try {

InetAddress host = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]);

String fileName = args[2].trim();

String request = "GET " + fileName + " HTTP/1.0\n\n"; MyStreamSocket mySocket = new MyStreamSocket(host, port);

/**/ System.out.println("Connection made"); mySocket.sendMessage(request); // now receive the response from the HTTP server

String response;

response = mySocket.receiveMessage(); // read and display one line at a time while (response != null) {

System.out.println(response); response = mySocket.receiveMessage(); }

} // end try catch (Exception ex) {

System.out.println("ERROR : " + ex) ; ex.printStackTrace(System.out); } // end catch }// end else }// end main } //end class Send() Receive()

Process A

Process B

GET filename HTTP/1.0\n\n response 1\r\n response2\r\n Receive() response3\n\n Receive() 31

HTTP Requests

~ GET

: for retrieving the contents of web object

referenced by the specified URI

~

HEAD

: for retrieving a header from the server only, not

the object itself.

~

POST

: used to send data to a process on the server

host.

~

PUT

: used to request the server to store the contents

enclosed with the request to the server machine in the

file location specified by the URI.



Request Example:

POST /servlet/myServer.servlet HTTP/1.0

Host: somehost.com

User-Agent: Generic

<blank line>

Name=donald&[email protected]

32

HTTP Responses



The status code designations are as follows:

100-199 Informational

200-299 Client request successful

300-399 Client request redirected

400-499 Client request incomplete

500-599 Server errors



Response Example:

HTTP/1.0 200 OK

Date: Sat, 15 Sep 2001 06:55:30 GMT

Server: Apache/1.3.9 (Unix) ApacheJServ/1.0

Last-Modified: Mon, 30 Apr 2001 23:02:36 GMT

Content-Length: 236

Content-Type: text/html

<html>

<head>

<title>My web page </title>

</head>

<body>

Hello world!

</BODY></HTML>

(9)

33

Java URL Class

Representa un Universal Resource Locator:

http://java.sun.com:80/javase/index.html

Method/Constructor

Description

URL(String spec)

Creates a

URL

object from the URL

name contained in a

String

URL(String protocol,

String host,

int port,String file)

Creates a

URL

object from the

specified

protocol

,

host

,

port

number, and

file

.

URLConnection

openConnection()

Returns a

URLConnection

object

that represents a connection to the

remote object referred to by the

URL

.

InputStream openStream()

Opens a connection to this

URL

and

returns an

InputStream

for reading

from that connection. Equivante to:

openConnection().getInputStream()

protocolo

dirección

puerto

camino +nombre fichero

34 import java.net.*;

import java.io.*; public class URLBrowser {

public static void main(String[] args) { if (args.length != 3)

System.out.println

("This program requires 3 command line arguments"); else {

try {

String host = args[0]; String port = args[1].trim(); String fileName = args[2].trim();

String HTTPString = "http://"+host+":"+port+"/"+fileName; URL theURL = new URL(HTTPString);

InputStream inStream = theURL.openStream( ); BufferedReader input = new BufferedReader

(new InputStreamReader(inStream)); String response;

response = input.readLine(); // read and display one line at a time while (response != null) {

System.out.println(response); response = input.readLine(); } //end while

}

catch (Exception ex) { } }// end else }// end main } //end class 35

URLConnection / HttpURLConnection

URLConnection

: Representa a connection to a URL.

HttpURLConnection

Sub-clases de la anterior. Contiene métodos

específicos para conexiones HTTP.

Method/Constructor

Description

connect()

Opens a communications link to the

resource referenced by this URL, if

such a connection has not already been

established

String getHeaderField (String

name)

Returns the value of the named header

field.

Method/Constructor

Description

setRequestMethod(String

method)

Set the method for the URL request,

one of: GET POST HEAD OPTIONS

PUT DELETE TRACE are legal,

subject to protocol restrictions.

int

getResponseCode()

Gets the status code from an HTTP

Referencias

Documento similar

In addition, precise distance determinations to Local Group galaxies enable the calibration of cosmological distance determination methods, such as supernovae,

Cu 1.75 S identified, using X-ray diffraction analysis, products from the pretreatment of the chalcocite mineral with 30 kg/t H 2 SO 4 , 40 kg/t NaCl and 7 days of curing time at

Authors: Pedro Manuel Moreno-Marcos, Dánae Martínez de la Torre, Gabriel González Castro, Pedro J.. Muñoz-Merino and Carlos

Astrometric and photometric star cata- logues derived from the ESA HIPPARCOS Space Astrometry Mission.

The photometry of the 236 238 objects detected in the reference images was grouped into the reference catalog (Table 3) 5 , which contains the object identifier, the right

In addition to traffic and noise exposure data, the calculation method requires the following inputs: noise costs per day per person exposed to road traffic

The value specified is the maximum time it takes the signal detect to assert after a step increase in the optical power into the receiver (measured with the data pattern specified

Quantitative data show 2 groups of seeds related to the length, corresponding to the minor values with the taxa previously included in the genus Nigritella, but the number