First off, I never been good at networking. I have manage to get TCP/IP to work, but never really used UDP, so sorry for any beginner mistakes. Anyway, I have starter to make my own game, and decided to use UDP, since it doesn’t really matter if some data get lost. However, so far it’s not really as fire and forget as I had hoped.
This is difficult for me to explain, but I’ll do my best. So I created a “Client” object, which contains a simple send method, which sends data via this little code
byte[] bytes = data.getBytes();
DatagramPacket pack = new DatagramPacket(bytes, bytes.length, adress, port);
client.send(pack);
then I assumed the server would send the data back via the same DatagramSocket, and I knew that .receive freezes the method/game until it manage to receive something. So I made a different thread for it
@Override
public void run() {
if(true){
try{
byte[] buffer = new byte[1024];
DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
client.receive(pack);
String sData = new String(pack.getData());
read(sData, pack);
}catch(Exception e){
e.printStackTrace();
}
}
}
But it never receive’s anything, I had to change my send code for me to be able to receive the message from the server.
public void send(InetAddress adress, int port, String data, boolean receive){
try{
//Send data to the server
byte[] bytes = data.getBytes();
DatagramPacket pack = new DatagramPacket(bytes, bytes.length, adress, port);
client.send(pack);
//This is my make shift code to get the reply from the server.
//Sadly if this doesn't get a reply it freezes the game.
if(receive){
//Wait to receive an answer
byte[] buffer = new byte[1024];
DatagramPacket back = new DatagramPacket(buffer, buffer.length);
client.receive(back);
read(new String(back.getData()), back);
}
//Somehow it doesn't send the data without this
Thread.sleep(1);
}catch(Exception e){
e.printStackTrace();
}
}
Am I missing something here, if UDP is suppose to fire and forget, why do I need to wait for a response? or am I not understanding something here?
P.S The server send code is
public void send(String data, InetAddress address, int port){
try{
//Just a simple send data function, not much to it.
byte[] sendData = data.getBytes();
DatagramPacket send = new DatagramPacket(sendData, sendData.length, address, port);
server.send(send);
}catch(IOException e){
}
}