Example usage for java.net Socket setTrafficClass

List of usage examples for java.net Socket setTrafficClass

Introduction

In this page you can find the example usage for java.net Socket setTrafficClass.

Prototype

public void setTrafficClass(int tc) throws SocketException 

Source Link

Document

Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = "asdfasdfasdf\n";
    byte buf[] = str.getBytes();
    out.write(buf);//from  w w  w . j a  va2s .co m
    int c;
    while ((c = in.read()) != -1) {
        System.out.print((char) c);
    }

    s.setTrafficClass(1);
    System.out.println(s.getTrafficClass());

    s.close();
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in blocking mode.//  w ww.j  a v  a  2s  .c om
 * @since 1.4.5
 */
private void runBlocking(TheClient theClient) throws Exception {
    Socket client = null;
    ClientHandler _chPolled = null;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    //long stime = System.currentTimeMillis();
    //long etime = System.currentTimeMillis();
    while (true) {
        //etime = System.currentTimeMillis();
        //System.out.println("Time Taken: "+(etime-stime));
        client = server.accept();
        //stime = System.currentTimeMillis();

        if (linger < 0) {
            client.setSoLinger(false, 0);
        } else {
            client.setSoLinger(true, linger);
        }

        client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

        if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
            client.setTrafficClass(socketTrafficClass);//low delay=10
        }

        //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

        if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
            client.setSendBufferSize(getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
            //logger.fine("SendBufferSize: "+client.getSendBufferSize());
        }

        if (stopServer) {
            //Client connected when server was about to be shutdown.
            try {
                client.close();
            } catch (Exception e) {
            }
            break;
        }

        if (checkAccessConstraint(client) == false) {
            continue;
        }

        //Check if max connection has reached
        if (getSkipValidation() != true && maxConnection != -1
                && getClientHandlerPool().getNumActive() >= maxConnection) {
            theClient.setClientEvent(ClientEvent.MAX_CON_BLOCKING);
        } else {
            theClient.setClientEvent(ClientEvent.RUN_BLOCKING);
        }

        theClient.setTrusted(getSkipValidation());
        theClient.setSocket(client);
        theClient.setSocketChannel(client.getChannel()); //mostly null

        if (clientDataClass != null) {
            if (getClientDataPool() == null) {
                clientData = (ClientData) clientDataClass.newInstance();
            } else {
                clientData = (ClientData) getClientDataPool().borrowObject();
            }
            theClient.setClientData(clientData);
        }

        try {
            _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
            _chPolled.handleClient(theClient);
        } catch (java.util.NoSuchElementException nsee) {
            logger.warning("Could not borrow ClientHandler from pool. Error: " + nsee);
            logger.warning("Closing Socket [" + client + "] since no ClientHandler available.");
            client.close();
        }

        if (_chPolled != null) {
            try {
                getClientPool().addClient(_chPolled, true);
            } catch (java.util.NoSuchElementException nsee) {
                logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                //logger.warning("Closing Socket ["+client+"] since no Thread available.");
                //client.close();
                //returnClientHandlerToPool(_chPolled);
            }
            _chPolled = null;
        }
        client = null;

        //reset it back
        setSkipValidation(false);
    } //end of loop
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in non-blocking mode.//from www .j ava2  s  .c  om
 * @since 1.4.5
 */
private void runNonBlocking(TheClient theClient) throws Exception {
    int selectCount = 0;
    Iterator iterator = null;
    SelectionKey key = null;
    ServerSocketChannel serverChannel = null;
    SocketChannel socketChannel = null;
    Socket client = null;
    ClientHandler _chPolled = null;
    boolean stopServerProcessed = false;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();
    registerChannelRequestMap = new HashMap();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    while (true) {
        selectCount = selector.select(500);
        //selectCount = selector.select();//for testing

        //check for any pending registerChannel req.
        synchronized (registerChannelRequestMap) {
            if (registerChannelRequestMap.size() > 0) {
                RegisterChannelRequest req = null;
                Object hashkey = null;
                iterator = registerChannelRequestMap.keySet().iterator();
                while (iterator.hasNext()) {
                    hashkey = iterator.next();
                    req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey);
                    req.register(getSelector());
                }
                iterator = null;
                registerChannelRequestMap.clear();
            } //if
        } //sync

        if (stopServer == true && stopServerProcessed == false) {
            logger.warning("Closing " + getName());
            serverSocketChannel.close();
            stopServerProcessed = true;

            server = null;
            serverSocketChannel = null;

            setServiceState(Service.STOPPED);
            logger.warning("Closed " + getName());

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

        if (stopServer == false && stopServerProcessed == true) {
            logger.finest("Server must have re-started.. will break");
            break;
        }

        if (selectCount == 0 && stopServerProcessed == true) {
            java.util.Set keyset = selector.keys();
            if (keyset.isEmpty() == true && getClientCount() <= 0) {
                break;
            } else {
                continue;
            }
        } else if (selectCount == 0) {
            continue;
        }

        iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            key = (SelectionKey) iterator.next();

            if (key.isValid() == false) {
                iterator.remove();
                continue;
            }

            if (key.isAcceptable() && stopServer == false) {
                logger.finest("Key is Acceptable");
                serverChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverChannel.accept();

                if (socketChannel == null) {
                    iterator.remove();
                    continue;
                }

                client = socketChannel.socket();

                if (linger < 0) {
                    client.setSoLinger(false, 0);
                } else {
                    client.setSoLinger(true, linger);
                }

                client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

                if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
                    client.setTrafficClass(socketTrafficClass);//low delay=10
                }

                //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

                if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
                    client.setSendBufferSize(
                            getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
                    //logger.fine("SendBufferSize: "+client.getSendBufferSize());
                }

                if (checkAccessConstraint(client) == false) {
                    iterator.remove();
                    continue;
                }

                socketChannel.configureBlocking(false);
                theClient.setTrusted(getSkipValidation());
                theClient.setSocket(socketChannel.socket());
                theClient.setSocketChannel(socketChannel);

                if (clientDataClass != null) {
                    if (getClientDataPool() == null) {
                        clientData = (ClientData) clientDataClass.newInstance();
                    } else {
                        //borrow a object from pool
                        clientData = (ClientData) getClientDataPool().borrowObject();
                    }
                    theClient.setClientData(clientData);
                }

                //Check if max connection has reached
                if (getSkipValidation() != true && maxConnection != -1
                        && getClientHandlerPool().getNumActive() >= maxConnection) {
                    theClient.setClientEvent(ClientEvent.MAX_CON);
                } else {
                    theClient.setClientEvent(ClientEvent.ACCEPT);
                }

                try {
                    _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
                    logger.finest("Asking " + _chPolled.getName() + " to handle.");
                    _chPolled.handleClient(theClient);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee);
                    logger.warning("Closing SocketChannel [" + serverChannel.socket()
                            + "] since no ClientHandler available.");
                    socketChannel.close();
                }

                if (_chPolled != null) {
                    try {
                        getClientPool().addClient(_chPolled, true);
                    } catch (java.util.NoSuchElementException nsee) {
                        logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                        //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available.");
                        //socketChannel.close();
                        //returnClientHandlerToPool(_chPolled);
                    }
                    _chPolled = null;
                }
                socketChannel = null;
                client = null;

                setSkipValidation(false);//reset it back
            } else if (key.isValid() && key.isReadable()) {
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName());
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    _ch.addEvent(ClientEvent.READ);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.READ);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (key.isValid() && key.isWritable()) {
                if (getClientPool().shouldNioWriteHappen() == false) {
                    continue; //no need to remove the key
                }
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName());
                    //remove OP_WRITE from interest set
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    _ch.addEvent(ClientEvent.WRITE);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.WRITE);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (stopServer == true && key.isAcceptable()) {
                //we will not accept this key
                setSkipValidation(false);//reset it back
            } else {
                logger.warning("Unknown key got in SelectionKey: " + key);
            }
            iterator.remove(); //Remove key

            Thread.yield();
        } //end of iterator
        iterator = null;
    } //end of loop
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Sets socket attributes on the socket.
 * @param socket The socket./*from   w w w  . j av a  2  s.  co  m*/
 * @throws SocketException
 */
protected void setSocketAttributes(Socket socket) throws SocketException {
    if (this.soTimeout >= 0) {
        socket.setSoTimeout(this.soTimeout);
    }
    if (this.soSendBufferSize > 0) {
        socket.setSendBufferSize(this.soSendBufferSize);
    }
    if (this.soReceiveBufferSize > 0) {
        socket.setReceiveBufferSize(this.soReceiveBufferSize);
    }
    socket.setTcpNoDelay(this.soTcpNoDelay);
    if (this.soLinger >= 0) {
        socket.setSoLinger(true, this.soLinger);
    }
    if (this.soTrafficClass >= 0) {
        socket.setTrafficClass(this.soTrafficClass);
    }
    socket.setKeepAlive(this.soKeepAlive);
}