It's weird that I use WireShark to test the result, and the result shows that my code can successfully send messages via socket. But my program will throw a Timeout
exception even if I receive the message from the server.
I don't know why there is a timeout problem.
My code is simple:
static Timer timer = new Timer();
try {
DatagramSocket c = new DatagramSocket();
c.setBroadcast(true);
byte[] sendData = "messageToServer".getBytes();
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 10000);
c.connect(InetAddress.getByName("255.255.255.255"), 10000);
c.send(sendPacket);
} catch(Exception ex) {
System.out.println(ex.toString());
}
timer.schedule(new receiveTask(), 2000);
} catch(Exception ex) {
System.out.println(ex.toString());
}
I use a timer to delay the reception of the message from the server.
The receiveTask
class looks like this:
public class receiveTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
try {
DatagramSocket c2 = new DatagramSocket();
c2.setSoTimeout(10000);
byte[] recvBuf = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
String message = "";
while (true) {
c2.receive(receivePacket);
System.out.println("Receive packet from Server");
message=new String(receivePacket.getData()).trim();
System.out.println(message);
System.out.println("Close the connection of server socket");
}
} catch(Exception ex) {
System.out.println(ex.toString());
}
}
}
And a SocketTimeOut
exception is thrown in the receiveTask
class.
Since the server can send a message to me (tested in WireShark), I don't think the fult is server-side. But what can cause the time-out?
Why the server returns a message to me but I can't receive it in my program?
My Java version is 7, and it makes no difference disabling the firewall on my computer...
Any advice will be appreciated!
Edit: Though the problem isn't about socket.close(); I remvoe the code.