简体   繁体   中英

set timeout for socket receive

I want to send data to server, then wait for an answer for one minute and then close the socket.

How to do it?

 DatagramPacket sendpack = new ......;
 socket.send(pack);
 DatagramPacket recievepack = new .....;
 //wait 1 minute{
 socket.recieve(buf);
 //wait 1 minute}
 socket.close();

You can try this. Change the timeout of the socket as required in your scenario! This code will send a message and then wait to receive messages until the timeout is reached!

DatagramSocket s;

    try {
        s = new DatagramSocket();
        byte[] buf = new byte[1000];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        InetAddress hostAddress = InetAddress.getByName("localhost");

        String outString = "Say hi";        // message to send
        buf = outString.getBytes();

        DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999);
        s.send(out);        // send to the server

        s.setSoTimeout(1000);   // set the timeout in millisecounds.

        while(true){        // recieve data until timeout
            try {
                s.receive(dp);
                String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "+ new String(dp.getData(), 0, dp.getLength());
                System.out.println(rcvd);
            }
            catch (SocketTimeoutException e) {
                // timeout exception.
                System.out.println("Timeout reached!!! " + e);
                s.close();
            }
        }

    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        //e1.printStackTrace();
        System.out.println("Socket closed " + e1);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If you are using DatagramSocket , or Socket you can use,

socket.setSoTimeout(1000); 
//the value is in milliseconds

For any detail, you should've taken a look in DatagramSocket javadoc or Socket javadoc .

To clarify EJP's comment, this is what he meant by a "missing break " causing a SocketException.

String group = "224.0.0.0";
int port = 5000;

MulticastSocket recvSock = new MulticastSocket(port);
recvSock.joinGroup(InetAddress.getByName(group));
recvSock.setSoTimeout(1000);

while(true) {
    try {
        recvSock.receive(in);               
    } catch (SocketTimeoutException e) {
        break;  // Closing here would cause a SocketException
    }
}

// Move the close() outside the try catch bloock
recvSock.leaveGroup(InetAddress.getByName(group));
recvSock.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM