Sunday, September 28, 2014

Java UDP: How to Send a File

Instructions

    1

    Create the base class to send the UDP datagram, with a main function. The class will use the "DatagramPacket," "DatagramSocket," and "InetAddress" libraries:

    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;

    class SendUDP

    public static void main(String[] args)


    2

    Create a new DatagramSocket and DatagramPacket in the main method. The datagram socket object will send the datagram packet object, which will get its information from the byte array "buffer":

    DatagramSocket s = new DatagramSocket();

    byte[] buf = new byte[1000];
    DatagramPacket out;
    3

    Create a sample message to send over UDP, and encode it into the byte array "buf:"

    String outString = "This is the message";
    buf = outString.getBytes();

    4

    Instantiate the "out" datagram packet with the buffer byte array containing the message, and point it towards the IP adress of the receiver, received through the "getByName" method. The number "9999" represents a port number open to UDP connections on the receiver's end: this could be any port number, depending on the receiving server's configuration.

    InetAddress reciever = InetAddress.getByName("http://www.sun.java.com");

    DatagramPacket out = new DatagramPacket(buf, buf.length, receiver, 9999);

    5

    Send the packet. Now that the datagram packet contains information required to send, transmit it through the Datagram socket:

    s.send(out);



No comments:

Post a Comment