设置套接字接收超时 [英] set timeout for socket receive

查看:171
本文介绍了设置套接字接收超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据发送到服务器,然后等待一分钟的答案,然后关闭套接字。

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

怎么做?

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

这篇关于设置套接字接收超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆