/*
 * This is a sample program that uses UDP to send text packets through the network.
 * If the command is run without a parameter, it is a receiver.
 * If it has a parameter, this must be the IP of the receiver the packet
 * is to go.
 */

/**
 *
 * @author skon
 */
// Demonstrate Datagrams.
import java.net.*;

class SenderReceiver {

    public static int senderPort = 8666;
    public static int receiverPort = 8667;
    public static int buffer_size = 1024;
    public static DatagramSocket ds;
    public static byte buffer[] = new byte[buffer_size];

    public static void TheSender(String address) throws Exception {
        int pos = 0;
        System.out.println("Sender Starts.");
        while (true) {
            int c = System.in.read();
            switch (c) {
                case -1:
                    System.out.println("Server Quits.");
                    return;
                case '\r':
                    break;
                case '\n':
                    ds.send(new DatagramPacket(buffer, pos,
                            InetAddress.getByName(address), receiverPort));
                    pos = 0;
                    break;
                default:
                    buffer[pos++] = (byte) c;
            }
        }
    }

    public static void TheReceiver() throws Exception {
        System.out.println("Receiver Starts.");
        while (true) {
            DatagramPacket p = new DatagramPacket(buffer,
                    buffer.length);
            ds.receive(p);
            System.out.println(new String(p.getData(), 0,
                    p.getLength()));
        }
    }

    public static void main(String args[]) throws Exception {
        if (args.length == 1) {
            System.out.println("Sending to: "+args[0]);
            ds = new DatagramSocket(senderPort);
            TheSender(args[0]); 
        } else {
            ds = new DatagramSocket(receiverPort);
            TheReceiver();
        }
    }
}
Topic revision: r2 - 2015-10-08 - BenjaminKindle
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback