Sistemas Distribuídos Java Sockets Departamento de Informática, UFMA Graduação em Ciência da Computação Francisco José da Silva e Silva 1 Introdução a Java Sockets Socket é o ponto final de um enlace de comunicação estabelecido entre dois programas que se comunicam em rede; Sua interface de programação utiliza o conceito de portas de comunicação. O socket é associado a um número de forma a tornar possível à camada TCP localizar a aplicação que deve receber os dados; Extensão de um dos conceitos mais fortes do Unix: toda E/S deve parecer ao programador como uma E/S de arquivo; O pacote java.net disponibiliza as classes necessárias para programação com sockets em Java; Leitura recomendada: tutorial da Sun All About Sockets, disponível em: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html 1.1 Java Sockets: Classes TCP orientado a conexão java.net.socket java.net.serversocket UDP sem conexão java.net.datagrampacket java.net.datagramsocket 2 Java Sockets Orientado a Conexão O servidor executa em um computador específico e possui um socket associado a um número de porta; O servidor apenas escuta, aguardando que um cliente solicite o estabelecimento de uma conexão; O cliente deve conhecer em qual máquina o servidor está sendo executado e a porta no qual ele escuta. O servidor aceita a conexão e recebe um novo socket associado à mesma porta; 1
Ele necessita do novo socket para poder continuar escutando no socket original por requisições de conexão, enquanto atende o cliente já conectado; Do lado cliente, se a conexão foi aceita, um socket é criado para ser utilizado na comunicação com o servidor; O cliente e o servidor podem agora se comunicar, escrevendo e escutando em seus respectivos sockets: 2.1 Código Cliente O Cliente: 1. Cria o socket através do construtor da classe Socket; 2. Tenta estabelecer uma conexão com o servidor; 3. Uma vez estabelecida a conexão, envia e recebe fluxos de dados; 4. Quando a comunicação for concluida, fecha a conexão. 2.2 Código Servidor O Servidor: 1. Cria um ServerSocket; 2. Escuta no socket através do método accept(); 3. Uma vez estabelecida a conexão, envia e recebe fluxos de dados; 4. Quando a comunicação for concluida, fecha a conexão. 5. Tipicamente retorna ao passo 2. 2.3 Exemplo de Código Exemplo de código. uso de sockets com conexão: ClienteComConex~ao.java ServidorComConex~ao.java 2
2.4 java.net.socket Esta classe implementa sockets cliente que utilizam conexão. Alguns Construtores: Socket(InetAddress address, int port) Creates a stream socket and connects it to the specified port number at the specified IP address; Socket(InetAddress address, int port, InetAddress localaddr, int localport) Creates a socket and connects it to the specified remote address on the specified remote port; Socket(String host, int port) Creates a stream socket and connects it to the specified port number on the named host; Socket(String host, int port, InetAddress localaddr, int localport) Creates a socket and connects it to the specified remote host on the specified remote port. Alguns métodos: void close() Closes this socket; InetAddress getinetaddress() Returns the address to which the socket is connected; InetAddress getlocaladdress() Gets the local address to which the socket is bound; int getlocalport() Returns the local port to which this socket is bound; int getport() Returns the remote port to which this socket is connected; boolean isclosed() Returns the closed state of the socket; boolean isconnected() Returns the connection state of the socket. Os dados são enviados e recebidos através de fluxos de entrada e saída. Os seguintes métodos são utilizados: InputStream getinputstream() Returns an input stream for this socket. OutputStream getoutputstream() Returns an output stream for this socket. 2.5 java.net.serversocket Esta classe implementa socket servidor que utiliza conexão. Um socket servidor espera por requisições que venham da rede. Ele realiza operações baseadas na requsição e possivelmente envia os resultados ao requerente. Um Construtor: ServerSocket(int port) Creates a server socket, bound to the specified port. Alguns métodos: Socket accept() Listens for a connection to be made to this socket and accepts it; 3
void close() Closes this socket; InetAddress getinetaddress() Returns the local address of this server socket; int getlocalport() Returns the port on which this socket is listening; SocketAddress getlocalsocketaddress() Returns the address of the endpoint this socket is bound to, or null if it is not bound yet; boolean isbound() Returns the binding state of the ServerSocket; boolean isclosed() Returns the closed state of the ServerSocket; 3 Java Sockets sem Conexão Algumas aplicações não requerem o canal seguro de comunicação ponto-a-ponto provido pelo protocolo TCP; Nestes casos, a aplicação pode utilizar um modo de comunicação que entrega pacotes independentes cuja entrega e sequenciamento das mensagens não são garantidos; O protocolo UDP provê este serviço. 3.1 Classes Utilizadas Classes utilizadas: DatagramPacket: insere bytes em um pacote UDP denominado datagrama; DatagramSocket: envia e recebe datagramas UDP; Para enviar dados, insere-se os mesmos em um DatagramPacket, enviando-o através do DatagramSocket; Para receber dados, recebe-se um DatagramPacket através de um DatagramSocket, procedendo-se em seguida a remoção dos dados a partir do pacote; O mesmo tipo de socket é utilizado tanto no cliente quanto no servidor; Trabalha com pacotes individuais e não com fluxo: os dados enviados em um datagrama são enviados em um único pacote; O socket não é dedicado a uma única conexão. 3.2 Exemplo de Código Exemplo de código. uso de sockets sem conexão: ClienteSemConex~ao.java ServidorSemConex~ao.java 4
3.3 java.net.datagrampacket Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. Packet delivery is not guaranteed. Alguns Construtores: DatagramPacket(byte[] buf, int length) Constructs a DatagramPacket for receiving packets of length length. DatagramPacket(byte[] buf, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length length to the specified port number on the specified host. DatagramPacket(byte[] buf, int offset, int length) Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer. DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length length with offset ioffsetto the specified port number on the specified host. Alguns Métodos: InetAddress getaddress() Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. byte[] getdata() Returns the data buffer. int getlength() Returns the length of the data to be sent or the length of the data received. int getport() Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received. void setaddress(inetaddress iaddr) Sets the IP address of the machine to which this datagram is being sent. void setdata(byte[] buf) Set the data buffer for this packet. void setdata(byte[] buf, int offset, int length) Set the data buffer for this packet. void setlength(int length) Set the length for this packet. void setport(int iport) Sets the port number on the remote host to which this datagram is being sent. 3.4 java.net.datagramsocket A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order. Um Construtor: DatagramSocket(int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address. 5
Alguns Métodos: void close() Closes this datagram socket. InetAddress getinetaddress() Returns the address to which this socket is connected. InetAddress getlocaladdress() Gets the local address to which the socket is bound. int getlocalport() Returns the port number on the local host to which this socket is bound. SocketAddress getlocalsocketaddress() Returns the address of the endpoint this socket is bound to, or null if it is not bound yet. int getport() Returns the port for this socket. Métodos para envio e recebimento de pacotes: void receive(datagrampacket p) Receives a datagram packet from this socket. void send(datagrampacket p) Sends a datagram packet from this socket. 6