Package udp.src

Source Code of udp.src.Client

package udp.src;

import data.Bernoulli;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) {
        String host = "localhost";
        int port = 7999;
        if (args.length > 0) {
            host = args[0];
        }
        if (args.length > 1) {
            port = Integer.parseInt(args[1]);
        }

        Scanner scanner = new Scanner(System.in);
//        System.out.print("Introduceti n: ");
        int n = scanner.nextInt();

        try (DatagramSocket socket = new DatagramSocket();) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4048);
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeInt(n);
            out.close();

            byte[] bout = baos.toByteArray();
            InetAddress address = InetAddress.getByName(host);
            DatagramPacket packet = new DatagramPacket(bout, bout.length, address, port);
            socket.send(packet);

            byte[] bin = new byte[4048];
            packet = new DatagramPacket(bin, bin.length);
            socket.receive(packet);

            ByteArrayInputStream bais = new ByteArrayInputStream(bin);
            ObjectInputStream in = new ObjectInputStream(bais);
            Bernoulli bernoulli = (Bernoulli)in.readObject();
            in.close();
            bernoulli.print();
            socket.close();
        }
        catch(Exception e) {
            System.err.println("Client communication error: "+e.getMessage());
        }
    }
}
TOP

Related Classes of udp.src.Client

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.