2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.sal.streams.websockets;
11 import com.google.common.base.Preconditions;
12 import io.netty.bootstrap.ServerBootstrap;
13 import io.netty.channel.Channel;
14 import io.netty.channel.EventLoopGroup;
15 import io.netty.channel.nio.NioEventLoopGroup;
16 import io.netty.channel.socket.nio.NioServerSocketChannel;
17 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * {@link WebSocketServer} is responsible to start and stop web socket server
24 public class WebSocketServer implements Runnable {
26 private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
27 public static final int DEFAULT_PORT = 8181;
28 private EventLoopGroup bossGroup;
29 private EventLoopGroup workerGroup;
30 private static WebSocketServer instance = null;
31 private int port = DEFAULT_PORT;
33 private WebSocketServer(int port) {
38 * Create instance of {@link WebSocketServer}
41 * TCP port used for this server
42 * @return instance of {@link WebSocketServer}
44 public static WebSocketServer createInstance(int port) {
45 Preconditions.checkState(instance == null, "createInstance() has already been called");
46 Preconditions.checkArgument(port > 1024, "Privileged port (below 1024) is not allowed");
48 instance = new WebSocketServer(port);
53 * Return websocket TCP port
55 public int getPort() {
60 * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}
62 * @return instance of {@link WebSocketServer}
64 public static WebSocketServer getInstance() {
65 Preconditions.checkNotNull(instance, "createInstance() must be called prior to getInstance()");
70 * Destroy this already created instance
72 public static void destroyInstance() {
73 Preconditions.checkState(instance != null, "createInstance() must be called prior to destroyInstance()");
81 bossGroup = new NioEventLoopGroup();
82 workerGroup = new NioEventLoopGroup();
84 ServerBootstrap b = new ServerBootstrap();
85 b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
86 .childHandler(new WebSocketServerInitializer());
88 Channel ch = b.bind(port).sync().channel();
89 logger.info("Web socket server started at port {}.", port);
91 ch.closeFuture().sync();
92 } catch (InterruptedException e) {
100 * Stops the web socket server and removes all listeners.
102 private void stop() {
103 Notificator.removeAllListeners();
104 if (bossGroup != null) {
105 bossGroup.shutdownGracefully();
108 if (workerGroup != null) {
109 workerGroup.shutdownGracefully();