Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在接收消息-套接字中添加超时_Java - Fatal编程技术网

Java 在接收消息-套接字中添加超时

Java 在接收消息-套接字中添加超时,java,Java,我有通过套接字发送消息和接收应答的方法。如何放置计时器,如果没有答案,例如1秒放置信息超时 public boolean SendForceMessage(final ForceMessageTCP message) { boolean result = true; System.out.println("******************SendForceMessage**********************************"); new Thread()

我有通过套接字发送消息和接收应答的方法。如何放置计时器,如果没有答案,例如1秒放置信息超时

public boolean SendForceMessage(final ForceMessageTCP message) {
    boolean result = true;
    System.out.println("******************SendForceMessage**********************************");
    new Thread() {
        public void run() {
            try {
                System.out.println("IPADDRESS="+ipAddress);
                System.out.println("PORT="+port);
                System.out.println("Is reachable="+Ping());

                for(int i=0;i<message.ToBytes().length;i++)
                    System.out.println("FRAGMENT["+i+"]="+message.ToBytes()[i]);

                socket = new Socket(ipAddress, port);
                OutputStream socketOutputStream = (OutputStream) socket
                        .getOutputStream();
                socketOutputStream.write(message.ToBytes());

                InputStream socketInputStream=(InputStream)socket.getInputStream();
                byte[] buffer=new byte[256];
                int numberReceived=socketInputStream.read(buffer);
                if(numberReceived!=-1)
                    new FDResponseMessage(buffer);


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

        }
    }.start();

    return result;
}
公共布尔SendForceMessage(最终ForceMessageTCP消息){
布尔结果=真;
System.out.println(“*************************************************************************************”);
新线程(){
公开募捐{
试一试{
System.out.println(“IPADDRESS=“+IPADDRESS”);
System.out.println(“端口=”+端口);
System.out.println(“可访问=”+Ping());
对于(int i=0;i

快乐阅读

编辑

忘记了插座选项,请检查此项:)

基本上,您将设置为SO,因此对read()的调用只会在指定的时间内阻塞

快乐阅读

编辑

忘记了插座选项,请检查此项:)

基本上,您将设置为SO,因此对read()的调用只会在指定的时间内阻塞