package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
public class UDPPollingServer {
public static void main(String[] args) throws NumberFormatException, IOException {
byte[] buf = new byte[2048];
DatagramSocket s = new DatagramSocket(Integer.parseInt(args[0]));
s.setSoTimeout(60000);
DatagramPacket p = new DatagramPacket(buf, buf.length);
int trump = 0, clinton =0, johnson = 0, stein = 0, blank=0;
List<String> candidats = new ArrayList<String>();
while(true){
s.receive(p);
InetAddress ia = p.getAddress();
String name = new String(p.getData(), p.getLength(), p.getOffset(), "UTF-8" );
// si on lit en ASCII le programme de vote n'est pas portable et selon les machines
// des votes pourraient être mal lues et donc comptés blanc
if(name.equals("quit" )){ //arrêt du serveur
break;
}
if(name.equals("clinton" )){
clinton++;
p.setData(Integer.toBinaryString(clinton).getBytes());
}
else if(name.equals("trump" )){
trump++;
p.setData(Integer.toBinaryString(trump).getBytes());
}
else if(name.equals("johnson" )){
johnson++;
p.setData(Integer.toBinaryString(johnson).getBytes());
}
else if(name.equals("stein" )){
stein++;
p.setData(Integer.toBinaryString(stein).getBytes());
}
else{
blank++;
p.setData(Integer.toBinaryString(blank).getBytes());
}
s.send(p);
System.out.println("Trump = "+trump);
System.out.println("Clinton = "+clinton);
System.out.println("Johnson = "+johnson);
System.out.println("Stein = "+stein);
System.out.println("Blanc = "+blank);
s.close();
}
}
}