List of usage examples for java.nio.channels SelectionKey OP_READ
int OP_READ
To view the source code for java.nio.channels SelectionKey OP_READ.
Click Source Link
From source file:org.apache.nifi.io.nio.ChannelListener.java
/** * Binds to listen for data grams on the given local IPAddress/port and * restricts receipt of datagrams to those from the provided host and port, * must specify both. This improves performance for datagrams coming from a * sender that is known a-priori.//w ww. jav a 2 s . c o m * * @param nicIPAddress - if null will listen on wildcard address, which * means datagrams will be received on all local network interfaces. * Otherwise, will bind to the provided IP address associated with some NIC. * @param port - the port to listen on. This is used to provide a well-known * destination for a sender. * @param receiveBufferSize - the number of bytes to request for a receive * buffer from OS * @param sendingHost - the hostname, or IP address, of the sender of * datagrams. Only datagrams from this host will be received. If this is * null the wildcard ip is used, which means datagrams may be received from * any network interface on the local host. * @param sendingPort - the port used by the sender of datagrams. Only * datagrams from this port will be received. * @throws IOException if unable to add channel */ public void addDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize, final String sendingHost, final Integer sendingPort) throws IOException { if (sendingHost == null || sendingPort == null) { addDatagramChannel(nicIPAddress, port, receiveBufferSize); return; } final DatagramChannel dChannel = createAndBindDatagramChannel(nicIPAddress, port, receiveBufferSize); dChannel.connect(new InetSocketAddress(sendingHost, sendingPort)); dChannel.register(socketChannelSelector, SelectionKey.OP_READ); }
From source file:org.commoncrawl.io.NIOSocketSelector.java
/** * poll method - poll the registered socket for events and potentially block * for IO for the specified timeout value * /*from w w w .jav a 2 s . c o m*/ * @param timeoutValue * - amount of time in MS to wait (block) for IO * * */ public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException { long timeStart = System.currentTimeMillis(); if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) { LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime)); } _lastPollTime = timeStart; if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime = 0; timeUsageDetailOut.unblockedTime = 0; } if (_selector == null || !_selector.isOpen()) { IOException e = new IOException("Selector NULL or Selector is Not Open!"); LOG.error(e); throw e; } processPendingRegistrations(); long timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (timeEnd - timeStart); } timeStart = System.currentTimeMillis(); int count = _selector.select(timeoutValue); timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime += (timeEnd - timeStart); } long unblockedTimeStart = System.currentTimeMillis(); // if (count != 0 ) { Set<SelectionKey> selectionSet = _selector.selectedKeys(); for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) { SelectionKey selectionKey = i.next(); i.remove(); if (selectionKey.isValid()) { NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { // reset interest ops selectionKey.interestOps(0); // process events in key ... if (selectionKey.isConnectable()) { boolean connected = false; Exception disconnectException = null; try { if (((NIOClientSocket) theSocket).finishConnect()) { connected = true; // log it ... // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress()); // reset the selection key's ops.. otherwise, select keeps // returning on an already connected socket (since we have // registered for CONNECT) System.out.println( "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress()); timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Connected((NIOClientSocket) theSocket); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis() - timeStart; } } else { // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() // + " - finishConnect returned false"); theSocket.close(); } } catch (IOException e) { // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() // + " with Exception:"+e); theSocket.close(); disconnectException = e; } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Connected Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); disconnectException = e; // KILL THE SERVER throw e; } // if we were unable to properly establish the connection, trigger // the Disconnected notification ... if (!connected) { // LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected"); ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, disconnectException); // continue to the next socket ... continue; } } // now always set the socket to readable state ... if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) { selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ); } if (selectionKey.isValid() && selectionKey.isReadable()) { int bytesRead = -1; try { timeStart = System.currentTimeMillis(); // track the number of actual bytes read in the callback ... bytesRead = ((NIOClientSocketListener) theSocket.getListener()) .Readable((NIOClientSocket) theSocket); // System.out.println("Readable Took:" + // (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart; } if (bytesRead == -1) { // log it ... // LOG.error("Abnormal Disconnect Detected on Socket:"+ // ((NIOClientSocket)theSocket).getSocketAddress()); // trigger a disconnect event ... ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, null); // close the socket ... theSocket.close(); } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); // KILL THE SERVER throw e; } // if bytesRead == -1 then this means that the underlying connection // has gone bad ... } if (selectionKey.isValid() && selectionKey.isWritable()) { try { timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Writeable((NIOClientSocket) theSocket); // System.out.println("Writable Took:" + // (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart; } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); // KILL THE SERVER throw e; } } if (selectionKey.isValid() && selectionKey.isAcceptable()) { ((NIOServerSocket) theSocket).acceptable(); // re-register for accept on this socket selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT); } } } else { LOG.error("Invalid Socket Detected. Calling Disconnect"); NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { theSocket.getListener().Disconnected(theSocket, null); } } } long unblockedTimeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart); } // } return count; }
From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java
protected void doScan() { try {/*from w w w . j a v a 2 s . c om*/ if (!isScanning) { isScanning = true; if (selector != null) { selector.close(); } if (broadcastChannel != null) { broadcastChannel.close(); } selector = Selector.open(); broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET) .setOption(StandardSocketOptions.SO_REUSEADDR, true) .setOption(StandardSocketOptions.SO_BROADCAST, true); broadcastChannel.configureBlocking(false); broadcastChannel.socket().setSoTimeout(BROADCAST_TIMEOUT); broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT)); SelectionKey broadcastKey = broadcastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); networkJob = scheduler.schedule(networkRunnable, 0, TimeUnit.MILLISECONDS); source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32); logger.debug("The LIFX discovery service will use '{}' as source identifier", Long.toString(source, 16)); GetServiceRequest packet = new GetServiceRequest(); packet.setSequence(SERVICE_REQUEST_SEQ_NO); packet.setSource(source); broadcastPacket(packet, broadcastKey); } else { logger.info("A discovery scan for LIFX light is already underway"); } } catch (Exception e) { logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage()); } }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
private void establishConnection() { lock.lock();// www. ja v a2s . co m try { if (getConfig().get(IP_ADDRESS) != null && getConfig().get(PORT_NUMBER) != null) { try { socketChannel = SocketChannel.open(); socketChannel.socket().setKeepAlive(true); socketChannel.configureBlocking(false); synchronized (selector) { selector.wakeup(); int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT; socketChannelKey = socketChannel.register(selector, interestSet); } InetSocketAddress remoteAddress = new InetSocketAddress((String) getConfig().get(IP_ADDRESS), ((BigDecimal) getConfig().get(PORT_NUMBER)).intValue()); socketChannel.connect(remoteAddress); } catch (IOException e) { logger.debug("An exception occurred while connecting to '{}:{}' : {}", getConfig().get(IP_ADDRESS), ((BigDecimal) getConfig().get(PORT_NUMBER)).intValue(), e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } try { Thread.sleep(((BigDecimal) getConfig().get(RESPONSE_TIME_OUT)).intValue()); } catch (NumberFormatException | InterruptedException e) { Thread.currentThread().interrupt(); logger.debug("An exception occurred while putting a thread to sleep: '{}'", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } onConnectable(); } } finally { lock.unlock(); } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java
/** * ?, ?, ?, ??//from w ww . j a v a 2 s .co m * @throws IOException * @throws InterruptedException */ private void dispatch() throws IOException, InterruptedException { logger.debug("try dispatch"); SelectionKey key = null; key = opsChangeRequest.getChannel().keyFor(selector); if (key != null) { if ((opsChangeRequest.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // key.interestOps(SelectionKey.OP_WRITE); opsChangeRequest.clearOps(SelectionKey.OP_WRITE); } else if ((opsChangeRequest.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { key.interestOps(SelectionKey.OP_READ); opsChangeRequest.clearOps(SelectionKey.OP_READ); } } // ?, isWeakuped.set(false); if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) { return; } // ? Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); iterator.remove(); if (!key.isValid()) { continue; } else if (key.isReadable()) { onRead(key); } else if (key.isWritable()) { onWrite(key); } } }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processConnect(SelectionKey key) throws Exception { SocketChannel ch = (SocketChannel) key.channel(); if (ch.finishConnect()) { key.interestOps(key.interestOps() ^ SelectionKey.OP_CONNECT); key.interestOps(key.interestOps() | SelectionKey.OP_READ); reconnectInterval = INITIAL_RECONNECT_INTERVAL; connected.set(true);// ww w . j a va 2s. c o m onConnected(); } }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected void updateReadInterest(NIOClientSocketHandler clientHandler, Selector selector) { SocketChannel socketChannel = clientHandler.getSocketChannel(); if (!socketChannel.isOpen()) return;//from w w w . j a v a 2 s.co m if (!socketChannel.isConnected()) return; // We are interested in reading only if we have some buffer space left if (clientHandler.getInputBuffer().remaining() > 0) addInterest(socketChannel, SelectionKey.OP_READ, clientHandler, selector); else removeInterest(socketChannel, SelectionKey.OP_READ, selector); }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private void doRecv(SelectionKey sockKey, ByteBuffer response) throws IOException { sockKey.interestOps(SelectionKey.OP_READ); SocketChannel sock = (SocketChannel) sockKey.attachment(); int totalRead = response.remaining(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (remainingMs > 0) { selector.select(remainingMs);//from ww w .j a v a2 s. com for (SelectionKey key : selector.selectedKeys()) { if (key.isReadable()) { sock.read(response); } } if (response.remaining() == 0) { if (LOG.isTraceEnabled()) { LOG.trace("Received all " + totalRead + " bytes from " + conf.endpointStr); } return; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (LOG.isTraceEnabled()) { LOG.trace("Received " + (totalRead - response.remaining()) + " out of " + totalRead + " bytes from " + conf.endpointStr); } if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }
From source file:com.web.services.ExecutorServiceThread.java
public void run() { // create a selector that will by used for multiplexing. The selector // registers the socketserverchannel as // well as all socketchannels that are created String CLIENTCHANNELNAME = "clientChannel"; String SERVERCHANNELNAME = "serverChannel"; String channelType = "channelType"; ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>(); ClassLoader classLoader = null; ByteArrayOutputStream bstr;// w w w . j a v a 2s.c o m ByteBuffer buffer = null; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); int bytesRead; InputStream bais; ObjectInputStream ois; Object object; ExecutorServiceInfo executorServiceInfo = null; Random random = new Random(System.currentTimeMillis()); // register the serversocketchannel with the selector. The OP_ACCEPT // option marks // a selection key as ready when the channel accepts a new connection. // When the // socket server accepts a connection this key is added to the list of // selected keys of the selector. // when asked for the selected keys, this key is returned and hence we // know that a new connection has been accepted. try { Selector selector = Selector.open(); SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // SelectionKey socketServerSelectionKey1 = // channel.register(selector1, // SelectionKey.OP_ACCEPT); // set property in the key that identifies the channel Map<String, String> properties = new ConcurrentHashMap<String, String>(); properties.put(channelType, SERVERCHANNELNAME); socketServerSelectionKey.attach(properties); // wait for the selected keys SelectionKey key = null; Set<SelectionKey> selectedKeys; // logger.info("Instance Number"+instanceNumber); Iterator<SelectionKey> iterator = null; SocketChannel clientChannel = null; while (true) { try { // the select method is a blocking method which returns when // atleast // one of the registered // channel is selected. In this example, when the socket // accepts // a // new connection, this method // will return. Once a socketclient is added to the list of // registered channels, then this method // would also return when one of the clients has data to be // read // or // written. It is also possible to perform a nonblocking // select // using the selectNow() function. // We can also specify the maximum time for which a select // function // can be blocked using the select(long timeout) function. if (selector.select() >= 0) { selectedKeys = selector.selectedKeys(); iterator = selectedKeys.iterator(); } while (iterator.hasNext()) { try { key = iterator.next(); // the selection key could either by the // socketserver // informing // that a new connection has been made, or // a socket client that is ready for read/write // we use the properties object attached to the // channel // to // find // out the type of channel. if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) { // a new connection has been obtained. This // channel // is // therefore a socket server. ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // accept the new connection on the server // socket. // Since // the // server socket channel is marked as non // blocking // this channel will return null if no client is // connected. SocketChannel clientSocketChannel = serverSocketChannel.accept(); if (clientSocketChannel != null) { // set the client connection to be non // blocking clientSocketChannel.configureBlocking(false); SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE); Map<String, String> clientproperties = new ConcurrentHashMap<String, String>(); clientproperties.put(channelType, CLIENTCHANNELNAME); clientKey.attach(clientproperties); clientKey.interestOps(SelectionKey.OP_READ); // clientSocketChannel.close(); // write something to the new created client /* * CharBuffer buffer = * CharBuffer.wrap("Hello client"); while * (buffer.hasRemaining()) { * clientSocketChannel.write * (Charset.defaultCharset() * .encode(buffer)); } * clientSocketChannel.close(); * buffer.clear(); */ } } else { // data is available for read // buffer for reading clientChannel = (SocketChannel) key.channel(); if (key.isReadable()) { // the channel is non blocking so keep it // open // till // the // count is >=0 clientChannel = (SocketChannel) key.channel(); if (resultMap.get(key) == null) { //System.out.println(key); bstr = new ByteArrayOutputStream(); object = null; clientChannel.read(lengthBuffer); int length = lengthBuffer.getInt(0); lengthBuffer.clear(); //System.out.println(length); buffer = ByteBuffer.allocate(length); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } buffer.clear(); //System.out.println("Message1"+new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ois = new ObjectInputStream(bais); // Offending // line. // Produces // the // StreamCorruptedException. //System.out.println("In read obect"); object = ois.readObject(); //System.out.println("Class Cast"); //System.out.println("Class Cast1"); ois.close(); byte[] params = bstr.toByteArray(); bstr.close(); //System.out.println("readObject"); //System.out.println("After readObject"); if (object instanceof CloseSocket) { resultMap.remove(key); clientChannel.close(); key.cancel(); } // clientChannel.close(); String serviceurl = (String) object; String[] serviceRegistry = serviceurl.split("/"); //System.out.println("classLoaderMap" // + urlClassLoaderMap); //System.out.println(deployDirectory // + "/" + serviceRegistry[0]); int servicenameIndex; //System.out.println(earServicesDirectory // + "/" + serviceRegistry[0] // + "/" + serviceRegistry[1]); if (serviceRegistry[0].endsWith(".ear")) { classLoader = (VFSClassLoader) urlClassLoaderMap .get(earServicesDirectory + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]); servicenameIndex = 2; } else if (serviceRegistry[0].endsWith(".jar")) { classLoader = (WebClassLoader) urlClassLoaderMap .get(jarservicesDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } else { classLoader = (WebClassLoader) urlClassLoaderMap .get(deployDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } String serviceName = serviceRegistry[servicenameIndex]; // System.out.println("servicename:"+serviceName);; synchronized (executorServiceMap) { executorServiceInfo = (ExecutorServiceInfo) executorServiceMap .get(serviceName.trim()); } ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader(); classLoaderExecutorServiceInfo.setClassLoader(classLoader); classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo); resultMap.put(key, classLoaderExecutorServiceInfo); // key.interestOps(SelectionKey.OP_READ); // System.out.println("Key interested Ops"); // continue; } //Thread.sleep(100); /* * if (classLoader == null) throw new * Exception( * "Could able to obtain deployed class loader" * ); */ /* * System.out.println( * "current context classloader" + * classLoader); */ //System.out.println("In rad object"); bstr = new ByteArrayOutputStream(); lengthBuffer.clear(); int numberofDataRead = clientChannel.read(lengthBuffer); //System.out.println("numberofDataRead" // + numberofDataRead); int length = lengthBuffer.getInt(0); if (length <= 0) { iterator.remove(); continue; } lengthBuffer.clear(); //System.out.println(length); buffer = ByteBuffer.allocate(length); buffer.clear(); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } if (bytesRead <= 0 || bytesRead < length) { //System.out.println("bytesRead<length"); iterator.remove(); continue; } //System.out.println(new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap .get(key); ois = new ClassLoaderObjectInputStream( (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending // line. // Produces // the // StreamCorruptedException. object = ois.readObject(); ois.close(); bstr.close(); executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo(); //System.out // .println("inputStream Read Object"); //System.out.println("Object=" // + object.getClass()); // Thread.currentThread().setContextClassLoader(currentContextLoader); if (object instanceof ExecutorParams) { ExecutorParams exeParams = (ExecutorParams) object; Object returnValue = null; //System.out.println("test socket1"); String ataKey; ATAConfig ataConfig; ConcurrentHashMap ataServicesMap; ATAExecutorServiceInfo servicesAvailable; Socket sock1 = new Socket("0.0.0.0", Integer.parseInt(nodesport[random.nextInt(nodesport.length)])); OutputStream outputStr = sock1.getOutputStream(); ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr); NodeInfo nodeInfo = new NodeInfo(); nodeInfo.setClassNameWithPackage( executorServiceInfo.getExecutorServicesClass().getName()); nodeInfo.setMethodName(executorServiceInfo.getMethod().getName()); nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS()); NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam(); nodeInfoMethodParam.setMethodParams(exeParams.getParams()); nodeInfoMethodParam .setMethodParamTypes(executorServiceInfo.getMethodParams()); //System.out.println("Serializable socket="+sock); //nodeInfo.setSock(sock); //nodeInfo.setOstream(sock.getOutputStream()); objOutputStream.writeObject(nodeInfo); objOutputStream = new ObjectOutputStream(outputStr); objOutputStream.writeObject(nodeInfoMethodParam); ObjectInputStream objInputStream1 = new ObjectInputStream( sock1.getInputStream()); returnValue = objInputStream1.readObject(); objOutputStream.close(); objInputStream1.close(); sock1.close(); /*returnValue = executorServiceInfo .getMethod() .invoke(executorServiceInfo .getExecutorServicesClass() .newInstance(), exeParams.getParams());*/ // Thread.currentThread().setContextClassLoader(oldCL); // System.out.println("Written Value=" // + returnValue.toString()); resultMap.put(key, returnValue); } key.interestOps(SelectionKey.OP_WRITE); //System.out.println("Key interested Ops1"); } else if (key.isWritable()) { // the channel is non blocking so keep it // open // till the // count is >=0 //System.out.println("In write"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make // a // BAOS // stream ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the // stream Object result = resultMap.get(key); oos.writeObject(result); // write an object // to // the stream oos.flush(); oos.close(); byte[] objData = baos.toByteArray(); // get // the // byte // array baos.close(); buffer = ByteBuffer.wrap(objData); // wrap // around // the // data buffer.rewind(); // buffer.flip(); //prep for writing //System.out.println(new String(objData)); //while (buffer.hasRemaining()) clientChannel.write(buffer); // write resultMap.remove(key); buffer.clear(); key.cancel(); clientChannel.close(); //System.out.println("In write1"); numberOfServicesRequests++; //System.out.println("Key interested Ops2"); } } iterator.remove(); } catch (Exception ex) { ex.printStackTrace(); key.cancel(); clientChannel.close(); resultMap.remove(key); //ex.printStackTrace(); } } } catch (Exception ex) { //ex.printStackTrace(); } } } catch (Exception ex) { //ex.printStackTrace(); } }
From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java
public void unsubscribeFromWriteEvent(SelectionKey selectionKey) throws IOException { final SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); final OutgoingConnection outgoingConnection = (OutgoingConnection) selectionKey.attachment(); final SelectionKey newSelectionKey = socketChannel.register(this.selector, SelectionKey.OP_READ); newSelectionKey.attach(outgoingConnection); outgoingConnection.setSelectionKey(newSelectionKey); synchronized (this.connectionsToClose) { this.connectionsToClose.put(outgoingConnection, Long.valueOf(System.currentTimeMillis())); }/*from w w w. j a v a2s. c om*/ }