Package udp.src

Source Code of udp.src.Server

package udp.src;

import data.Bernoulli;

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

public class Server {

    public static void main(String[] args) {
        int port = 7999;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        Server server = new Server();
        DatagramSocket datagramSocket = server.getDatagramSocket(port);
        server.myAction(datagramSocket);
    }

    public DatagramSocket getDatagramSocket(int port) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(port);
        }
        catch(IOException e) {
            System.err.println("Could not create DatagramSocket on port: " + port);
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("DatagramSocket is ready ...");
        return datagramSocket;
    }

    public void myAction(DatagramSocket datagramSocket) {
        while(true) {
            try {
                byte[] bin = new byte[4048];
                DatagramPacket packet = new DatagramPacket(bin, bin.length);
                datagramSocket.receive(packet);

                ByteArrayInputStream bais = new ByteArrayInputStream(bin);
                ObjectInputStream in = new ObjectInputStream(bais);
                int n = in.readInt();
                in.close();
                Bernoulli bernoulli = new Bernoulli(n);

                ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
                ObjectOutputStream out = new ObjectOutputStream(baos);
                out.writeObject(bernoulli);
                out.close();

                byte[] bout = baos.toByteArray();
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(bout, bout.length, address, port);
                datagramSocket.send(packet);
            }
            catch(Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

}
TOP

Related Classes of udp.src.Server

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.