Example usage for java.net SocketOptions SO_TIMEOUT

List of usage examples for java.net SocketOptions SO_TIMEOUT

Introduction

In this page you can find the example usage for java.net SocketOptions SO_TIMEOUT.

Prototype

int SO_TIMEOUT

To view the source code for java.net SocketOptions SO_TIMEOUT.

Click Source Link

Document

Set a timeout on blocking Socket operations:
 ServerSocket.accept(); SocketInputStream.read(); DatagramSocket.receive(); 

The option must be set prior to entering a blocking operation to take effect.

Usage

From source file:mamo.vanillaVotifier.VotifierServer.java

public synchronized void start() throws IOException {
    if (isRunning()) {
        throw new IllegalStateException("Server is already running!");
    }/*from ww w. j a v  a  2s  .c  om*/
    notifyListeners(new ServerStartingEvent());
    serverSocket = new ServerSocket();
    serverSocket.bind(votifier.getConfig().getInetSocketAddress());
    running = true;
    notifyListeners(new ServerStartedEvent());
    new Thread(new Runnable() {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            while (isRunning()) {
                try {
                    final Socket socket = serverSocket.accept();
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                notifyListeners(new ConnectionEstablishedEvent(socket));
                                socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch.
                                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(socket.getOutputStream()));
                                writer.write("VOTIFIER 2.9\n");
                                writer.flush();
                                BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch.
                                byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair()
                                        .getPublic()).getModulus().bitLength() / Byte.SIZE];
                                in.read(request); // IOException: handled by try/catch.
                                notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request)));
                                request = RsaUtils
                                        .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate())
                                        .doFinal(request); // IllegalBlockSizeException: can't happen.
                                String requestString = new String(request);
                                notifyListeners(new DecryptedInputReceivedEvent(socket, requestString));
                                String[] requestArray = requestString.split("\n");
                                if ((requestArray.length == 5 || requestArray.length == 6)
                                        && requestArray[0].equals("VOTE")) {
                                    notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1],
                                            requestArray[2], requestArray[3], requestArray[4])));
                                    for (VoteAction voteAction : votifier.getConfig().getVoteActions()) {
                                        String[] params = new String[4];
                                        try {
                                            for (int i = 0; i < params.length; i++) {
                                                params[i] = SubstitutionUtils.applyRegexReplacements(
                                                        requestArray[i + 1], voteAction.getRegexReplacements());
                                            }
                                        } catch (PatternSyntaxException e) {
                                            notifyListeners(new RegularExpressionPatternErrorException(e));
                                            params = new String[] { requestArray[1], requestArray[2],
                                                    requestArray[3], requestArray[4] };
                                        }
                                        if (voteAction.getCommandSender() instanceof RconCommandSender) {
                                            RconCommandSender commandSender = (RconCommandSender) voteAction
                                                    .getCommandSender();
                                            StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor(
                                                    new SimpleEntry<String, Object>("service-name", params[0]),
                                                    new SimpleEntry<String, Object>("user-name", params[1]),
                                                    new SimpleEntry<String, Object>("address", params[2]),
                                                    new SimpleEntry<String, Object>("timestamp", params[3]));
                                            for (String command : voteAction.getCommands()) {
                                                String theCommand = substitutor.replace(command);
                                                notifyListeners(new SendingRconCommandEvent(
                                                        commandSender.getRconConnection(), theCommand));
                                                try {
                                                    notifyListeners(new RconCommandResponseEvent(
                                                            commandSender.getRconConnection(), commandSender
                                                                    .sendCommand(theCommand).getPayload()));
                                                } catch (Exception e) {
                                                    notifyListeners(new RconExceptionEvent(
                                                            commandSender.getRconConnection(), e));
                                                }
                                            }
                                        }
                                        if (voteAction.getCommandSender() instanceof ShellCommandSender) {
                                            ShellCommandSender commandSender = (ShellCommandSender) voteAction
                                                    .getCommandSender();
                                            HashMap<String, String> environment = new HashMap<String, String>();
                                            environment.put("voteServiceName", params[0]);
                                            environment.put("voteUserName", params[1]);
                                            environment.put("voteAddress", params[2]);
                                            environment.put("voteTimestamp", params[3]);
                                            for (String command : voteAction.getCommands()) {
                                                notifyListeners(new SendingShellCommandEvent(command));
                                                try {
                                                    commandSender.sendCommand(command, environment);
                                                    notifyListeners(new ShellCommandSentEvent());
                                                } catch (Exception e) {
                                                    notifyListeners(new ShellCommandExceptionEvent(e));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    notifyListeners(new InvalidRequestEvent(socket, requestString));
                                }
                            } catch (SocketTimeoutException e) {
                                notifyListeners(new ReadTimedOutExceptionEvent(socket, e));
                            } catch (BadPaddingException e) {
                                notifyListeners(new DecryptInputExceptionEvent(socket, e));
                            } catch (Exception e) {
                                notifyListeners(new CommunicationExceptionEvent(socket, e));
                            }
                            try {
                                socket.close();
                                notifyListeners(new ConnectionClosedEvent(socket));
                            } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close.
                                notifyListeners(new ConnectionCloseExceptionEvent(socket, e));
                            }
                        }
                    });
                } catch (Exception e) {
                    if (running) { // Show errors only while running, to hide error while stopping.
                        notifyListeners(new ConnectionEstablishExceptionEvent(e));
                    }
                }
            }
            executorService.shutdown();
            if (!executorService.isTerminated()) {
                notifyListeners(new ServerAwaitingTaskCompletionEvent());
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                } catch (Exception e) {
                    // InterruptedException: can't happen.
                }
            }
            notifyListeners(new ServerStoppedEvent());
        }
    }).start();
}

From source file:org.jnode.net.ipv4.tcp.TCPSocketImpl.java

/**
 * @see java.net.SocketOptions#getOption(int)
 *///from  www. j  av  a2  s . c o  m
public Object getOption(int option_id) throws SocketException {
    switch (option_id) {
    case SocketOptions.SO_BINDADDR:
        return controlBlock.getLocalAddress().toInetAddress();
    case SocketOptions.SO_RCVBUF:
        return controlBlock.getReceiveBufferSize();
    case SocketOptions.SO_SNDBUF:
        return controlBlock.getSendBufferSize();
    case SocketOptions.SO_TIMEOUT:
        // todo implement it, 0 means disabled
        return 0;
    default:
        throw new SocketException("Option " + option_id + " is not recognised or not implemented");
    }
}