I'm programming a multiplayer game in java and want to see available servers in the current network by doing a multicast. The problem is that as soon as I start the Multicast Server the Frontend stops responding and I'm forced to close the window. I'm using JavaFX.
Anyone with an idea?
Thanks in advance!
package server;
import backend.game.Game;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
// Multicast Server telling clients he is available for connection
public class MulticastReceiver extends Thread{
protected MulticastSocket socket = null;
protected byte[] buf = new byte[256];
public InetAddress group;
private Game game;
//main for testing
public static void main(String[] args) {
try {
MulticastReceiver mr = new MulticastReceiver(new Game(InetAddress.getLocalHost().getHostAddress(), "Milans test game"));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public MulticastReceiver(Game game){
this.game = game;
this.run();
}
@Override
/**
* @author mestorff
* Thread listening for messages coming in on IP 230.0.0.0 and handeling them
*/
public void run(){
try {
socket = new MulticastSocket(4446);
group = InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
socket.setReuseAddress(true);
while(!Thread.interrupted() && !socket.isClosed()){
DatagramPacket packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
//System.out.println(received);
if("end".equals(received)){
break;
}
String multicastAnswer = game.getGameID() + ":" + game.getGameName();
byte[] bufAnswer = multicastAnswer.getBytes();
DatagramPacket answerPacket = new DatagramPacket(bufAnswer, bufAnswer.length, packet.getAddress(), packet.getPort());
socket.send(answerPacket);
Thread.sleep(3000);
}} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @author mestorff
* Stop Thread and close socket
*/
public void stopThread(){
this.interrupt();
try {
socket.leaveGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}