Baixe o app para aproveitar ainda mais
Prévia do material em texto
package sockets.TCP; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; public class PessoaInputStream { /** * @param args * @throws */ public static void main(String[] args) { String nome = "Lucas"; StringReader sr = null; BufferedReader br = null; try{ sr = new StringReader(nome); br = new BufferedReader(sr); System.out.println((char)br.read()); System.out.println((char)br.read()); //marco este ponto br.mark(0); System.out.println("mark() invoked"); System.out.println((char)br.read()); System.out.println((char)br.read()); // volto para o ponto marcado br.reset(); System.out.println("reset() invoked"); System.out.println((char)br.read()); System.out.println((char)br.read()); } catch (Exception e) { // exception occurred. e.printStackTrace(); }finally{ // releases any system resources associated with the stream if(sr!=null) sr.close(); if(br!=null) try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String cpf = "123.111.134-56"; StringReader sr2 = null; BufferedReader br2 = null; try{ sr2 = new StringReader(cpf); br2 = new BufferedReader(sr2); System.out.println((char)br2.read()); System.out.println((char)br2.read()); //marco este ponto br2.mark(0); System.out.println("mark() invoked"); System.out.println((char)br2.read()); System.out.println((char)br2.read()); // volto para o ponto marcado br.reset(); System.out.println("reset() invoked"); System.out.println((char)br2.read()); System.out.println((char)br2.read()); } catch (Exception e) { // exception occurred. e.printStackTrace(); }finally{ // releases any system resources associated with the stream if(sr2!=null) sr2.close(); if(br2!=null) try { br2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String idade = "20"; StringReader sr3 = null; BufferedReader br3 = null; try{ sr3 = new StringReader(idade); br3 = new BufferedReader(sr3); System.out.println((char)br3.read()); System.out.println((char)br3.read()); //marco este ponto br3.mark(0); System.out.println("mark() invoked"); System.out.println((char)br3.read()); System.out.println((char)br3.read()); // volto para o ponto marcado br3.reset(); System.out.println("reset() invoked"); System.out.println((char)br3.read()); System.out.println((char)br3.read()); } catch (Exception e) { // exception occurred. e.printStackTrace(); }finally{ // releases any system resources associated with the stream if(sr3!=null) sr3.close(); if(br3!=null) try { br3.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package sockets.TCP; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class PessoaOutputStream { public static void main(String[] args) throws IOException { ServerSocket servidor = new ServerSocket(12345); Socket cliente = servidor.accept(); Scanner entrada = new Scanner(cliente.getInputStream()); while (entrada.hasNextLine()) { System.out.println(entrada.nextLine()); } entrada.close(); servidor.close(); } } package ping; import java.io.*; import java.net.*; import java.util.*; /* * Servidor para processar as requisições de Ping sobre UDP. */ public class PingServer { private static final double LOSS_RATE = 0.3; private static final int AVERAGE_DELAY = 100;// milliseconds private static DatagramSocket socket; public static void main(String[] args) throws Exception { while (true) { // Obter o argumento da linha de comando. if (args.length != 1) { System.out.println("Required arguments: port"); return; } int port = Integer.parseInt(args[0]); // Gerador de números aleatórios p/ simular perda de pacotes e atrasos na rede. Random random = new Random(); socket = new DatagramSocket(port); byte[] buffer = new byte[1024]; // Criar um pacote de datagrama para comportar o pacote UDP de chegada. DatagramPacket request = new DatagramPacket(buffer, buffer.length); // Bloquear até que o hospedeiro receba o pacote UDP. socket.receive(request); // Imprimir os dados recebidos. printData(request); // Decidir se responde, ou simula perda de pacotes. if (random.nextDouble() < LOSS_RATE) { System.out.println("Reply not sent."); continue; } // Simular o atraso da rede. Thread.sleep((int) (random.nextDouble()) * 2 * AVERAGE_DELAY); // Enviar resposta. InetAddress clientHost = request.getAddress(); int clientPort = request.getPort(); byte[] buf = request.getData(); DatagramPacket reply = new DatagramPacket(buf, buf.length, clientHost, clientPort); socket.send(reply); System.out.println("Reply sent."); } } /* * Imprimir o dado de Ping para o trecho de saída padrão. */ private static void printData(DatagramPacket request) throws Exception { // Obter referências para a ordem de pacotes de bytes. byte[] buf = request.getData(); // Envolver os bytes numa cadeia de entrada vetor de bytes, de modo que // você possa ler os dados como uma cadeia de bytes. ByteArrayInputStream bais = new ByteArrayInputStream(buf); // Envolver a cadeia de saída do vetor bytes num leitor de cadeia de // entrada, de modo que você possa ler os dados como uma cadeia de // caracteres. InputStreamReader isr = new InputStreamReader(bais); // Envolver o leitor de cadeia de entrada num leitor com armazenagem, de // modo que você possa ler os dados de caracteres linha a linha. (A // linha é uma seqüência de caracteres terminados por alguma combinação // de \r e \n.) BufferedReader br = new BufferedReader(isr); // O dado da mensagem está contido numa única linha, então leia esta linha. String line = br.readLine(); // Imprimir o endereço do hospedeiro e o dado recebido dele. System.out.println("Received from " + request.getAddress().getHostAddress() + ":" + new String(line)); } } package sockets.TCP; public class Pessoa { public String nome; public String cpf; public int idade; } package sockets.TCP; import java.net.*; import java.io.*; public class TCPServer { publicstatic void main (String args[]) { try{ int serverPort = 7896; // the server port ServerSocket listenSocket = new ServerSocket(serverPort); while(true) { Socket clientSocket = listenSocket.accept(); Connection c = new Connection(clientSocket); } } catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());} } } class Connection extends Thread { DataInputStream in; DataOutputStream out; Socket clientSocket; public Connection (Socket aClientSocket) { try { clientSocket = aClientSocket; in = new DataInputStream( clientSocket.getInputStream()); out =new DataOutputStream( clientSocket.getOutputStream()); this.start(); } catch(IOException e) {System.out.println("Connection:"+e.getMessage());} } public void run(){ try { // an echo server String data = in.readUTF(); // read a line of data from the stream out.writeUTF(data.toUpperCase()); }catch (EOFException e){System.out.println("EOF:"+e.getMessage()); } catch(IOException e) {System.out.println("readline:"+e.getMessage()); } finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}} } } package sockets.TCP; import java.net.*; import java.io.*; public class TCPClient { public static void main (String args[]) { // arguments supply message and hostname Socket s = null; try{ int serverPort = 7896; s = new Socket("localhost", serverPort); DataInputStream in = new DataInputStream( s.getInputStream()); DataOutputStream out =new DataOutputStream( s.getOutputStream()); out.writeUTF("teste"); // UTF is a string encoding see Sn. 4.4 String data = in.readUTF(); // read a line of data from the stream System.out.println("Received: "+ data) ; }catch (UnknownHostException e){System.out.println("Socket:"+e.getMessage()); }catch (EOFException e){System.out.println("EOF:"+e.getMessage()); }catch (IOException e){System.out.println("readline:"+e.getMessage()); }finally {if(s!=null) try {s.close();}catch (IOException e){System.out.println("close:"+e.getMessage());}} } } Vou colocar a pasta no trabalho 1 também, pois a opção de envio está só pdf.
Compartilhar