1 / 13

Infra-Estrutura de Comunicação (IF678)

Infra-Estrutura de Comunicação (IF678). Bruno Gentilini (bgda) Eduardo Souza (efs) Luís Felipe Auto (lfag) . Caio Mc Intyre (cfmi) Lucas Ventura (lvs) Sérgio Pessoa (srpvnf). Aula Prática 02 Programação de Sockets TCP e UDP.

dale
Download Presentation

Infra-Estrutura de Comunicação (IF678)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Infra-Estrutura de Comunicação(IF678) Bruno Gentilini (bgda) Eduardo Souza (efs) Luís Felipe Auto (lfag) Caio Mc Intyre (cfmi) Lucas Ventura (lvs) Sérgio Pessoa (srpvnf) Aula Prática 02 Programação de Sockets TCP e UDP Professor: Paulo Gonçalves (pasg@cin.ufpe.br) CIn/UFPE

  2. Nosso objetivo: • Revisão sobre Socket • Programação de Sockets TCP e UDP • Desenvolver um servidor Web

  3. Agenda Comunicação entre processos Programação de Socket TCP Programação de Socket UDP Desenvolver um servidor Web...

  4. Comunicação entre processos • Processos em hosts distintos comunicam-se por meio de envio de mensagens... • enviadas e recebidas através de seu socket Socket é a interface entre a camada de aplicação e a de transporte

  5. Programação de Socket TCP - Client import java.io.*; import java.net.*; import java.util.Scanner; public class TCPclient { public static void main(String[] args) throws Exception { //lendo do teclado String inFromUser = new Scanner(System.in).next(); //criando um socket TCP Socket sock = new Socket("localhost", 2000); //stream de saida DataOutputStream socketOut = new DataOutputStream(sock.getOutputStream()); socketOut.writeBytes(inFromUser + '\n'); //resposta do servidor BufferedReader socketIn = new BufferedReader(new InputStreamReader(sock.getInputStream())); System.out.println(socketIn.readLine()); } }

  6. Programação de Socket TCP - Server importjava.io.*; importjava.net.*; publicclassTCPserver { publicstaticvoidmain(String argv[]) throws Exception { String inFromClient; String outToClient; //socket de "boas vindas" ServerSocketwelcomeSocket = newServerSocket(2000); while(true) { //socket de conexão TCP Socketsock = welcomeSocket.accept(); //buffer de entrada, que recebe um stream BufferedReadersocketIn = newBufferedReader(newInputStreamReader(sock.getInputStream())); inFromClient = socketIn.readLine(); outToClient = inFromClient.toUpperCase() + '\n'; //stream de saida DataOutputStreamsocketOut = newDataOutputStream(sock.getOutputStream());//stream de saida //escrevendo no socket socketOut.writeBytes(outToClient); sock.close(); } } }

  7. Exercício Faça um “Hello [endereço IP do servidor]” e retorne do servidor um “HELLO [endereço IP do cliente]” OBS: O cliente deve fechar a conexão após receber a resposta do servidor ou dar um timeout de 30 segundos.

  8. Programação de Socket UDP - Client importjava.net.*; importjava.util.Scanner; classUDPclient { publicstaticvoidmain(String args[]) throws Exception { String inFromUser = new Scanner(System.in).next() + '\n'; //entrada do usuário DatagramSocketclientSocket = newDatagramSocket(); //socket UDP InetAddressIPServer = InetAddress.getByName("localhost"); //IP do servidor byte[] sendData = new byte[1024]; //dados a serem enviados sendData = inFromUser.getBytes(); //criando o pacote de envio DatagramPacketsendPacket = newDatagramPacket(sendData, sendData.length, IPServer, 5000); clientSocket.send(sendPacket); byte[] receiveData = new byte[1024]; //dados recebidos DatagramPacketreceivePacket = newDatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); //recebendo o pacote String inFromServer = new String(receivePacket.getData()); System.out.println("FROM SERVER: " + inFromServer); clientSocket.close(); } }

  9. Programação de Socket UDP - Server importjava.net.*; classUDPserver { publicstaticvoidmain(String args[]) throws Exception { DatagramSocketserverSocket = newDatagramSocket(5000); byte[] receiveData = new byte[1024] , sendData = new byte[1024]; String inFromClient, outToClient; InetAddressclientIP; intport; while(true) { //pacote a ser recebido DatagramPacketreceivePacket = newDatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); //recebendo o pacotes inFromClient = new String(receivePacket.getData()); //colocando na string os dados recebidos clientIP = receivePacket.getAddress(); //pegando o IP e porta do pacote que chegou port = receivePacket.getPort(); outToClient = inFromClient.toUpperCase(); sendData = outToClient.getBytes(); //enviandopacote de resposta DatagramPacketsendPacket = newDatagramPacket(sendData, sendData.length, clientIP, port); serverSocket.send(sendPacket); } } }

  10. Exercício • Faça, por meio de uma conexão UDP, o cliente enviar dois números e o servidor responder com a soma deles. • OBS: O cliente deve encerrar após receber a resposta do servidor ou dar um timeout de 30 segundos.

  11. Desenvolver um servidor Web... • Trata-se de um servidor Web, que responderá a requisições HTTP, bastante simples. Com as seguintes regras: • Deve ser implementado utilizando-se a API de Java • Ele deve manipular apenas uma requisição HTTP; • Ele deve enviar uma mensagem de resposta ao cliente contendo linhas de cabeçalho e o objeto desejado, se existente; • A única verificação necessária é quando o objeto não for encontrado, deve-se retornar: “HTTP/1.0 404 Not Found” • Teste seu servidor utilizando um navegador qualquer! • Mantenha os arquivos que serão baixados na mesma pasta do seu projeto • Dicas: - utilize as classes ServerSocket, Socket, StringTokenizer e File - reveja a aula sobre HTTP - consulte o RFC[2616] • baixar código parcial em www.cin.ufpe.br/~cfmi/comunicacao no link [Aulas]

  12. Exemplo – O que deve ser feito Requisição (via browser ou telnet) telnet: GET /index.html HTTP/1.0 Host: localhost Browser: http://ip:porta Resposta (seu servidor) HTTP/1.0 200 OK Content-Language: pt-BR Content-Length: 53 Content-Type: text/html Connection: close CRLF “enter” dados ... Requisição (via browser ou telnet) telnet: GET /img2.png HTTP/1.0 Host: localhost Browser: http://ip:porta Resposta (seu servidor) HTTP/1.0 200 OK Content-Language: pt-BR Content-Length: 733 Content-Type: image/png Connection: close CRLF “enter” dados ... 12

  13. Referências James F. Kurose and Keith W. Ross, "Redes de Computadores e a Internet - Uma Nova Abordagem", 3a. edição - 2005 - Ed. Addison Wesley BRA http://www.rfc.net/ http://www.ietf.org/rfc.html http://java.sun.com/j2se/1.5.0/docs/api/java/net/package-summary.html http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html Slides anteriores da monitoria feitos por flávio almeida (faas). 13

More Related