Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Capítulo 2 - Sistemas Distribuídos - Coulouris

4,501 views

Published on

Modelos fundamentais e arquiteturais de um sistema distribuído

Published in: Education
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/qURD } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/qURD } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download doc Ebook here { https://soo.gd/qURD } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Capítulo 2 - Sistemas Distribuídos - Coulouris

  1. 1. 1 SMD0050 - SISTEMAS DISTRIBUÍDOS - Capítulo 2•Prof. Dr. Windson Viana de Carvalho•Créditos : 64h•Prática e Teórica
  2. 2. 2Modelagem e projeto de um sistemadistribuído• Muitos desafios a serem suplantados• Projetar um SD em três perspectivas • Modelos Físicos • Hardware envolvido (rede e dispositivos) • Modelos Arquiteturais • Camadas de software e distribuição entre as entidades envolvidas • Modelos Fundamentais • Quais estratégias serão utilizadas para garantir a coordenação, a segurança e dependabilidade do sistema distribuído?
  3. 3. 3Modelos Físicos• Três Gerações de Sistemas distribuídos • Fase I : Acesso Remoto e Compartilhamento de recursos • Fase II: Sistemas baseados na Internet • Fase III: Sistemas contemporâneos em larga escala com grande heterogeneidade de acesso• Sistema de Terceira Geração podem servistos como Sistemas de Sistemas ouSistemas Complexos
  4. 4. Figure 2.1Gerações de Sistemas distribuídos Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012 4
  5. 5. 5Modelos Arquiteturais• Organização ou estrutura que responde àsseguintes questões • Quais são entidades (software) e seus papéis na execução das tarefas do sistema distribuído? • Como essas entidades irão se conectar e qual paradigma de comunicação será utilizado? • Onde as entidades estarão fisicamente localizadas?
  6. 6. 6Modelos Arquiteturais• Quais são entidades comunicantes em um SD? • Processos • Entidade de software comunicante • Pode conter subprocessos (Threads) • Nós físicos • Sensores, sistemas de automação• Do ponto de vista de desenvolvimento de um SD • Objetos • Componentes • Serviços
  7. 7. 7Modelos Arquiteturais• Como essas entidades irão se conectar e qual paradigma de comunicação será utilizado?• A resposta está muitas vezes relacionada a tecnologia de desenvolvimento utilizada• Comunicação entre processos• Invocação remota• Comunicação indireta
  8. 8. 8Comunicação entre processos• A forma mais simples é uso de APIs para acessar a camada de sockets do sistema operacional • Problemas inerentes a desconexões, não presença e protocolo de troca de informação ficam a cargo do programador• Modelos de conexão atrelados ao protocolo de transporte • Socket TCP, socket UDP • Uso de Multicast ou Unicast• Suporte a modelo com conexão permanente e manutenção de estado de conexão• Protocolos de troca de mensagens • Separadores • Serialização e deserialização • XML, JSON
  9. 9. 9Exemplo de Serialização em Javaclass Nodo implements Serializable { Vector filhos; Nodo pai; String nome;public Nodo(String s) { filhos = new Vector(5); nome = s; } public void addFilho(Nodo n) {Filhos.addElement(n); n.pai = this; }}
  10. 10. 10Exemplo de Serialização em Javacliente = new Socket(host, port); Nodo top = new Nodo("topo"); top.addFilho(new Nodo("filho1")); top.addFilho(new Nodo("filho2")); ObjectOutput out = new ObjectOutputStream(cliente.getOutputStream()); out.writeObject(top);out.flush();
  11. 11. 11Exemplo de Serialização em JavaCliente - Socketcliente = new Socket(host, port);Nodo top = new Nodo("topo");top.addFilho(new Nodo("filho1"));top.addFilho(new Nodo("filho2"));ObjectOutput out = new ObjectOutputStream(cliente.getOutputStream());out.writeObject(top);out.flush();
  12. 12. 12Exemplo de Serialização em JavaServidor - Socketsocket = server.accept();out = new ObjectOutputStream(socket.getOutputStream());in = new ObjectInputStream(socket.getInputStream());Nodo n = (Nodo)in.readObject();n.addFilho(new Nodo("servidor"));out.writeObject(n);out.flush();
  13. 13. 13Invocação remota• Framework de mais alto nível disponível pelo Sistema Operacional ou middleware para facilitar a comunicação entre processos • Protocolos do tipo requisição-resposta • Remote Procedure Call (RPC) • Remote Method Invocation (RMI)
  14. 14. 14Exemplo: RMI Java
  15. 15. 15Desvantagens da Invocaçãoremota• Um acoplamento entre as partes comunicantes ainda é grande • Conhecimento de quem está comunicando • Ambos conectados ao mesmo tempo • Pode oferecer transparência de localização e acesso usando descoberta de serviços
  16. 16. 16Comunicação indireta• Menor acoplamento entre os sistemas• Promove os desacoplamentos espacial e temporal • Sem a necessidade de conhecimento da localização e com quem está se comunicando • Sem a necessidade de os comunicantes estarem conectados ao mesmo• Exemplos • Sistemas baseados em eventos (Event-based ou Publish- Subscribers) • Fila de Mensagens • Espaço de Tuplas • Memória Compartilhada e Distribuída
  17. 17. 17Paradigmas de comunicação Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  18. 18. 18Modelos Arquiteturais• Estilos Arquiteturais • Arquitetura Cliente-Servidor • Cliente magro ou cliente gordo • Proxy • Múltiplos servidores • Arquitetura Peer-to-Peer • Totalmente descentralizada • Hierárquica
  19. 19. Arquitetura Cliente-Servidor Client invocation invocation Server result result Server Client Key: Process: Computer: Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  20. 20. Thin client (Cliente “magro”) Compute serverNetwork computer or PC Thin network Application Client Process Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  21. 21. Serviço provido por múltiplosservidores Service Server Client Server Client Server Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  22. 22. Uso de Servidores Proxy Client Web server Proxy server Client Web server Vantagens e Desvantagens? Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  23. 23. Arquitetura Peer-to-Peer (P2P) Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  24. 24. 24Padrões Arquiteturais• Arquiteturas recorrentes me SD • Arquitetura em camadas • Arquitetura Two-Tier • Arquitetura Three-Tier • Arquitetura Web Services
  25. 25. Representação Arquitetural emCamadas Applications, services Middleware Operating system Platform Computer and network hardware Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  26. 26. 26Arquiteturas Two-tier e Three-tier Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  27. 27. Arquitetura padrão de Web 27Services Instructor’s Guide for Coulouris, Dollimore, Kindberg and Blair, Distributed Systems: Concepts and Design Edn. 5 © Pearson Education 2012
  28. 28. 28Relembrando • Sockest TCP
  29. 29. Programação de socketusando TCPServiço TCP: transferência confiável de bytes de um processo para outro controlado pelo controlado pelo processo desenvolvedor desenvolvedor processo da aplicação da aplicação socket socket TCP com TCP com controlado controlado buffers, pelo sistema pelo sistema buffers, Internet variáveis operacional operacional variáveis hospedeiro hospedeiro ou servidor ou servidor
  30. 30. Programaçãode socket com TCPcliente deve contactar servidor • quando contactado pelo cliente,• processo servidor primeiro deve servidor TCP cria novo socket estar rodando para processo servidor se• servidor deve ter criado socket comunicar com cliente (porta) que aceita contato do • permite que servidor fale com cliente múltiplos clientes • números de porta de origemcliente contacta servidor: usados para distinguir clientes• criando socket TCP local ao (mais no Cap. 3) cliente• especificando endereço IP, # ponto de vista da aplicação porta do processo servidor TCP oferece transferência• quando cliente cria socket: de bytes confiável, em ordem cliente TCP estabelece conexão (“pipe”) entre cliente e servidor com servidor TCP
  31. 31. Interação de socketcliente/servidor: TCP servidor (rodando em hostid) Cliente cria socket, porta = x, para requisição que chega: welcomeSocket = ServerSocket() estabelecimento cria socket, espera requisição da conexão que chega da conexão TCP conexão com hostid, porta = x clientSocket = connectionSocket = Socket() welcomeSocket.accept() envia requisição usando lê requisição de clientSocket connectionSocket escrever resposta em connectionSocket lê resposta de clientSocket fecha connectionSocket fecha clientSocket
  32. 32. Programação de socket com TCPExemplo de apl. cliente-servidor:1) cliente lê linha da entrada padrão (cadeia inFromUser), envia ao servidor via socket (cadeia outToServer)2) servidor lê linha do socket3) servidor converte linha para maiúsculas, envia de volta ao cliente4) cliente lê, imprime linha modificada do socket (cadeia inFromServer)
  33. 33. Exemplo: cliente Java (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[ ]) throws Exception { String sentence; String modifiedSentence; cria cadeia BufferedReader inFromUser = de entrada new BufferedReader(new InputStreamReader(System.in)); cria socket cliente, conexão Socket clientSocket = new Socket("hostname", 6789); com servidor cria cadeia de DataOutputStream outToServer = saída conectada new DataOutputStream(clientSocket.getOutputStream()); ao socket
  34. 34. cria cadeia de BufferedReader inFromServer =entrada conectada new BufferedReader(new ao socket InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); envia linha outToServer.writeBytes(sentence + n); ao servidor modifiedSentence = inFromServer.readLine(); lê linha do servidor System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
  35. 35. Exemplo: servidor Java (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; cria socket de String capitalizedSentence; apresentação na ServerSocket welcomeSocket = new ServerSocket(6789); porta 6789 while(true) { espera no socketde apresentação pelo Socket connectionSocket = welcomeSocket.accept(); contato do cliente BufferedReader inFromClient = cria cadeia de new BufferedReader(new entrada, conectada InputStreamReader(connectionSocket.getInputStream())); ao socket
  36. 36. cria cadeia desaída, conectada DataOutputStream outToClient = ao socket new DataOutputStream(connectionSocket.getOutputStream()); lê linha do socket clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + n; escreve linha outToClient.writeBytes(capitalizedSentence); no socket } } } fim do loop while, retorna e espera outra conexão do cliente

×