aula01TCliente

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

//emissor
public class Cliente {
    public static void main (String args[]){
        // CHECK FOR VALID NUMBER OF PARAMETERS
        int argc = args.length;
        if (argc != 1){
            System.out.println ("Syntax :");
            System.out.println ("java PacketSendDemo hostname");
            return;
        }
        String hostname = args[0];
        try{
            System.out.println ("Binding to a local port");

            // CREATE A DATAGRAM SOCKET, BOUND TO ANY AVAILABLE LOCAL PORT
            DatagramSocket socket = new DatagramSocket();
            System.out.println ("Bound to local port " + socket.getLocalPort());

            byte[] barray = "Greetings!".getBytes();

            // CREATE A DATAGRAM PACKET, CONTAINING OUR BYTE ARRAY
            DatagramPacket packet = new DatagramPacket( barray, barray.length );
            System.out.println ("Looking up hostname " + hostname );

            // LOOKUP THE SPECIFIED HOSTNAME, AND GET AN INETADDRESS
            InetAddress addr = InetAddress.getByName(hostname);
            System.out.println ("Hostname resolved as "+addr.getHostAddress());

            // ADDRESS PACKET TO SENDER
            packet.setAddress(addr);

            // SET PORT NUMBER TO 2000
            packet.setPort(2000);

            // SEND THE PACKET - REMEMBER NO GUARANTEE OF DELIVERY
            socket.send(packet);
            System.out.println ("Packet sent!");
        }catch (UnknownHostException e){
            System.err.println ("Can't find host " + hostname);
        }catch (IOException e){
            System.err.println ("Error - " + e);
        }
    }
}
Tags : ,

0 thoughts on “aula01TCliente”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.