3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.protocol_plugin.openflow.core.internal;
12 import java.io.IOException;
13 import java.nio.channels.SelectionKey;
14 import java.nio.channels.Selector;
15 import java.nio.channels.ServerSocketChannel;
16 import java.nio.channels.spi.SelectorProvider;
17 import java.util.Iterator;
19 import org.opendaylight.controller.protocol_plugin.openflow.core.IController;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 public class ControllerIO {
24 private static final Logger logger = LoggerFactory
25 .getLogger(ControllerIO.class);
26 private static Short defaultOpenFlowPort = 6633;
27 private Short openFlowPort;
28 private SelectionKey serverSelectionKey;
29 private IController listener;
30 private ServerSocketChannel serverSocket;
31 private Selector selector;
32 private boolean running;
33 private Thread controllerIOThread;
35 public ControllerIO(IController l) {
37 this.openFlowPort = defaultOpenFlowPort;
38 String portString = System.getProperty("of.listenPort");
39 if (portString != null) {
41 openFlowPort = Short.decode(portString).shortValue();
42 } catch (NumberFormatException e) {
43 logger.warn("Invalid port:" + portString + ", use default("
44 + openFlowPort + ")");
49 public void start() throws IOException {
52 this.selector = SelectorProvider.provider().openSelector();
53 // create the listening socket
54 this.serverSocket = ServerSocketChannel.open();
55 this.serverSocket.configureBlocking(false);
56 this.serverSocket.socket().bind(
57 new java.net.InetSocketAddress(openFlowPort));
58 this.serverSocket.socket().setReuseAddress(true);
59 // register this socket for accepting incoming connections
60 this.serverSelectionKey = this.serverSocket.register(selector,
61 SelectionKey.OP_ACCEPT);
62 controllerIOThread = new Thread(new Runnable() {
67 // wait for an incoming connection
69 Iterator<SelectionKey> selectedKeys = selector
70 .selectedKeys().iterator();
71 while (selectedKeys.hasNext()) {
72 SelectionKey skey = selectedKeys.next();
73 selectedKeys.remove();
74 if (skey.isValid() && skey.isAcceptable()) {
75 ((Controller) listener).handleNewConnection(selector,
79 } catch (Exception e) {
84 }, "ControllerI/O Thread");
85 controllerIOThread.start();
86 logger.info("Controller is now listening on port " + openFlowPort);
89 public void shutDown() throws IOException {
91 this.selector.wakeup();
92 this.serverSocket.close();