I'm developing a net game with udp socket (DatagramSocket) between two clients (the server notifies both the respective ip and the clients establish the connection). The problem is that the connection isn't working on all PCs. It works for some friends, but doesn't work for others. Denifitely the problem is sending.
Send hi is a function to send a sort message repeatedly to start the port (I discovered that to receive in UDP port it's necessary to send first), and send ack it just a confirmation to the "hi" (There is a process calling receive, and obviously i send and receive in the same port)
This would be the most important:
public class connection {
protected DatagramSocket socketUDP;
protected InetAddress address;
protected int timeout = 50;
protected int portSend;
protected byte[] bufReceive = new byte[65535];
protected byte[] bufSend;
private boolean isUDP = true;
public connection(String ip, int port, int timeout, boolean isUDP) {
this.isUDP = isUDP;
this.timeout = timeout;
try {
if(isUDP) {
socketUDP = new DatagramSocket(port);
this.portReceive = port;
if (timeout > 0) {
socketUDP.setSoTimeout(timeout);
}
address = InetAddress.getByName(ip);
}
else{
///
}
}catch (Exception e){
e.printStackTrace();
}
this.rec = new receiver(this);
this.rec.start();
}
private void send(int id, Object msg, boolean string){
if(isUDP) {
bufSend = (Integer.toString(id) + ";NR;" + (String)msg).getBytes();
DatagramPacket packet = new DatagramPacket(bufSend, bufSend.length, address, portSend);
try {
socketUDP.send(packet);
} catch (Exception e) {
e.printStackTrace();
}
}
else {
/////
}
}
public void receive(){
if(blockReception || socketUDP != null && !socketUDP.isConnected()){return;}
try {
if(isUDP) {
String received = "";
DatagramPacket packet
= new DatagramPacket(bufReceive, bufReceive.length);
socketUDP.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
received = new String(packet.getData(), 0, packet.getLength());
if(received.equals("HI")){
sendAck(msgID.toClient.hi);
return;
}
System.out.println(received)
}
else{
//////
}
}catch (Exception e){e.printStackTrace();}
}
public void setPortSend(int portSend) {
this.portSend = portSend;
if(isUDP) {
socketUDP.connect(address, portSend);
sendHi();
}
}
}
I hope someone can say me why it isn't working for all users.