簡體   English   中英

設置套接字接收超時

[英]set timeout for socket receive

我想向服務器發送數據,然后等待一分鍾的答復,然后關閉套接字。

怎么做?

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

你可以試試這個。 根據您的場景需要更改套接字的超時時間! 此代碼將發送一條消息,然后等待接收消息,直到達到超時!

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();
    }

如果您使用的是DatagramSocketSocket您可以使用,

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

有關任何詳細信息,您應該查看DatagramSocket javadocSocket javadoc

為了澄清 EJP 的評論,這就是他所說的導致 SocketException 的“缺失break ”的意思。

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM