protected void sendGuardSignal() throws IOException { final DatagramSocket guard; final DatagramPacket guardPacket; guard = new DatagramSocket(); guardPacket = new DatagramPacket(new byte[0], 0); guardPacket.setSocketAddress(getLocalAddress()); guard.send(guardPacket); guard.close(); }
// Broadcasts a packet containing server address to the LAN every second public void run() { try { DatagramSocket socket = new DatagramSocket(); InetSocketAddress address = new InetSocketAddress("255.255.255.255", DISCOVERY_PORT); byte[] message = new byte[0]; socket.setBroadcast(true); DatagramPacket packet = new DatagramPacket(message, message.length); packet.setSocketAddress(address); while (true) { socket.send(packet); Thread.sleep(1000); } } catch (IOException e) { // Port is in use, we don't know our own address or we could not send the broadcast for some // reason. Either way, discovery won't work. logger.log(Level.SEVERE, null, e); } catch (InterruptedException e) { logger.log(Level.INFO, "Discovery service shutting down"); } }
@Override public void run() { // Open for voting logger.log(Level.INFO, "Beginning voting"); voting.beginVoting(); VotingReceiver votingService = new VotingReceiver(); if (votingThread != null && !votingThread.isInterrupted()) { votingThread.interrupt(); } votingThread = new Thread(votingService); votingThread.start(); try { /*If client/server are on the same machine, broadcast may arrive at client * before server opens receive socket. This is not relevant on separate machines * but it avoids an extra voting cycle on single machine tests. */ Thread.sleep(200); // Broadcast start of voting period try { DatagramSocket socket = new DatagramSocket(); InetSocketAddress address = new InetSocketAddress("255.255.255.255", VOTING_PORT); byte[] message = new byte[0]; socket.setBroadcast(true); DatagramPacket packet = new DatagramPacket(message, message.length); packet.setSocketAddress(address); socket.send(packet); } catch (IOException e) { logger.log(Level.SEVERE, null, e); } Thread.sleep(10000); // Run voting for 10 seconds } catch (InterruptedException ex) { logger.log(Level.INFO, "Voting shutting down"); } votingThread.interrupt(); voting.endVoting(MCServer.this); }