Handles a web socket connection.

@param socket the opening socket.
180386
@Override
    public void handle(final ServerWebSocket socket) {
        LOGGER.info("New web socket connection {}, {}", socket, socket.uri());

        if (! configuration.accept(socket.uri())) {
            LOGGER.warn("Web Socket connection denied on {} by {}", socket.uri(), configuration.name());
            return;
        }

        final Socket sock = new Socket(socket);
        accessor.getDispatcher().addSocket(socket.path(), sock);

        socket.closeHandler(event -> {
            LOGGER.info("Web Socket closed {}, {}", socket, socket.uri());
            accessor.getDispatcher().removeSocket(socket.path(), sock);
        });

        socket.handler(event -> accessor.getDispatcher().received(socket.path(), event.getBytes(), sock));

    }
120353
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    winston.info('Control connection from %s opened', this.socket.remoteAddress);

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}
514260
public function handleConnection($socket)
    {
        stream_set_blocking($socket, 0);
        $client = $this->createConnection($socket);

        $timer = $this->loop->addTimer(5, function() use ($client) {
            $client->removeAllListeners('init');
            $client->end('Timeout waiting for PROXY header.');
            $this->emit('proxytimeout', [new Connection($client->stream, $this->loop)]);
        });

        $client->on('init', function($connection) use ($client, $timer) {
            $timer->cancel();
            $this->emit('connection', [$connection]);
        });
    }
1340491
private void manageInputBuffer(int source){
        //System.out.println(System.currentTimeMillis() + " manageInputBuffer -> "+source);
        switch (source) {
            case ControlSock:
                //System.out.println(System.currentTimeMillis() + " - receive Control");
                try {
                    //  Read input from socket
                    byte[] inputBuffer = controlSocket.recv(0);
                    manageControl(inputBuffer);
                    controlSocket.send("".getBytes(), 0);
                }
                catch (DevFailed e) {
                    controlSocket.send(e.errors[0].desc.getBytes(), 0);
                }
                catch (Exception e) {
                    e.printStackTrace();
                    controlSocket.send(e.toString().getBytes(), 0);
                }
                break;

            case HearBeatSock:
                //System.out.println(System.currentTimeMillis() + " - receive heartbeat");
                try {
                    //  Read input from socket (in 3 parts)
                    byte[][] inputs = readSocket(heartbeatSocket, 3);
                    manageHeartbeat(inputs);
                }
                catch (DevFailed e) {
                    Except.print_exception(e);
                }
                break;

            case EventSock:
                //System.out.println(System.currentTimeMillis() + " - receive event  -----------------");
                try {
                    byte[][] inputs = readSocket(eventSocket, 4);
                    manageEvent(inputs);
                }
                catch (DevFailed e) {
                    Except.print_exception(e);
                }
                break;
        }
    }
720356
private void handleRequest(ByteBuf request, ChannelHandlerContext context) {
    NettyConnection connection = getConnection(context.channel());
    if (connection != null) {
      connection.handleRequest(request);
    }
  }
566367
public void connectSocket() {

        synchronized (lock) {
            if (isForegrounded) {
                if (socketConnection == null) {
                    SocketFactory factory = new SocketFactory(socketURI, new SocketEventDispatcher(listener, new Parser()).setLogger(log), log);
                    socketConnection = new SocketConnectionController(new Handler(Looper.getMainLooper()), dataMgr, factory, listener, new RetryStrategy(60, 60000), log);
                    socketConnection.setProxy(proxyURI);
                    socketConnection.connect();

                } else {
                    socketConnection.connect();
                }
                socketConnection.setManageReconnection(true);
            }
            lock.notifyAll();
        }
    }
1220444
function connect(socketURL) {
        disconnect().done(function () {
            _socket = new WebSocket(socketURL);
            _socket.onmessage = _onMessage;
            _socket.onopen = _onConnect;
            _socket.onclose = _onDisconnect;
            _socket.onerror = _onError;
        });
    }
2683
public function acceptConnection($socket)
    {
        // Accept a connection on server socket.
        set_error_handler(function(){});
        $new_socket = stream_socket_accept($socket, 0, $remote_address);
        restore_error_handler();

        // Thundering herd.
        if (!$new_socket) {
            return;
        }

        // TcpConnection.
        $connection                         = new TcpConnection($new_socket, $remote_address);
        $this->connections[$connection->id] = $connection;
        $connection->worker                 = $this;
        $connection->protocol               = $this->protocol;
        $connection->transport              = $this->transport;
        $connection->onMessage              = $this->onMessage;
        $connection->onClose                = $this->onClose;
        $connection->onError                = $this->onError;
        $connection->onBufferDrain          = $this->onBufferDrain;
        $connection->onBufferFull           = $this->onBufferFull;

        // Try to emit onConnect callback.
        if ($this->onConnect) {
            try {
                call_user_func($this->onConnect, $connection);
            } catch (\Exception $e) {
                static::log($e);
                exit(250);
            } catch (\Error $e) {
                static::log($e);
                exit(250);
            }
        }
    }
1088244
public void destroySocket(Socket s)
    {
        if (s == null) {
            return;
        }
        s.setLinger(linger);
        s.close();
        this.sockets.remove(s);
    }
166418
public void play(int port) throws IOException {
        if (acceptExecutor != null) {
            throw new IllegalStateException("play() already called");
        }
        // The acceptExecutor handles the Socket.accept() and hands each request off to the
        // requestExecutor. It also handles shutdown.
        acceptExecutor = Executors.newSingleThreadExecutor();
        // The requestExecutor has a fixed number of worker threads. In order to get strict
        // guarantees that requests are handled in the order in which they are accepted
        // workerThreads should be set to 1.
        requestExecutor = Executors.newFixedThreadPool(workerThreads);
        serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);

        this.port = serverSocket.getLocalPort();
        acceptExecutor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() {
            public void run() {
                try {
                    acceptConnections();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer connection failed", e);
                }

                /*
                 * This gnarly block of code will release all sockets and
                 * all thread, even if any close fails.
                 */
                try {
                    serverSocket.close();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer server socket close failed", e);
                }
                for (Iterator<Socket> s = openClientSockets.keySet().iterator(); s.hasNext(); ) {
                    try {
                        s.next().close();
                        s.remove();
                    } catch (Throwable e) {
                        logger.log(Level.WARNING, "MockWebServer socket close failed", e);
                    }
                }
                try {
                    acceptExecutor.shutdown();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer acceptExecutor shutdown failed", e);
                }
                try {
                    requestExecutor.shutdown();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer requestExecutor shutdown failed", e);
                }
            }

            private void acceptConnections() throws Exception {
                while (true) {
                    Socket socket;
                    try {
                        socket = serverSocket.accept();
                    } catch (SocketException e) {
                        return;
                    }
                    SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                    if (socketPolicy == DISCONNECT_AT_START) {
                        dispatchBookkeepingRequest(0, socket);
                        socket.close();
                    } else {
                        openClientSockets.put(socket, true);
                        serveConnection(socket);
                    }
                }
            }
        }));
    }
1090358
private void prepareStreams(Socket socket) throws IOException {

        // Close any open streams if I'm being called because a new socket was
        // set to handle this transport.
        try {
            if (dataInputStream != null) {
                dataInputStream.close();
            }
            if (dataOutputStream != null) {
                dataOutputStream.close();
            }
        }
        catch (IOException x) {
            // Do nothing.
        }

        dataInputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
        dataOutputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    }
1278125
@SuppressWarnings({"InfiniteLoopStatement", "ConstantConditions", "null"})
  public void run() {
    Socket client = null;
    while (true) {
      try {
        client = listener.accept();
        if (DEBUG) {
          System.err.print("Accepted request from ");
          System.err.println(client.getInetAddress().getHostName());
        }
        new Session(client);
      } catch (Exception e1) {
        System.err.println("NERServer: couldn't accept");
        e1.printStackTrace(System.err);
        try {
          client.close();
        } catch (Exception e2) {
          System.err.println("NERServer: couldn't close client");
          e2.printStackTrace(System.err);
        }
      }
    }
  }
775104
private void startConnecting()
    {
        //  Open the connecting socket.
        try {
            boolean rc = open();

            //  Connect may succeed in synchronous manner.
            if (rc) {
                handle = ioObject.addFd(fd);
                connectEvent();
            }
            //  Connection establishment may be delayed. Poll for its completion.
            else {
                handle = ioObject.addFd(fd);
                ioObject.setPollConnect(handle);
                socket.eventConnectDelayed(addr.toString(), -1);
            }
        }
        catch (RuntimeException | IOException e) {
            //  Handle any other error condition by eventual reconnect.
            if (fd != null) {
                close();
            }
            addReconnectTimer();
        }
    }
718041
public void handleConnect(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        String uri = request.getRequestURI();
        
        context.log("CONNECT: "+uri);
        
        InetAddrPort addrPort=new InetAddrPort(uri);
        
        //if (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
        //{
        //    sendForbid(request,response,uri);
        //}
        //else
        {
            InputStream in=request.getInputStream();
            OutputStream out=response.getOutputStream();
            
            Socket socket = new Socket(addrPort.getInetAddress(),addrPort.getPort());
            context.log("Socket: "+socket);
            
            response.setStatus(200);
            response.setHeader("Connection","close");
            response.flushBuffer();
            
            System.err.println(response);

            context.log("out<-in");
            IO.copyThread(socket.getInputStream(),out);
            context.log("in->out");
            IO.copy(in,socket.getOutputStream());
        }
    }
76295
private void closeServerSocket() {
       getLogger().debug("{} closing server socket", getName());

       try {
         if (serverSocket != null) {
           serverSocket.close();
         }
       } catch (Exception e) {
         // ignore for now
       }

       serverSocket = null;
     }
1177961
public void setSocket(Socket socket) {
	    if (socket != null)
	    {
	      m_remoteAddress = socket.getInetAddress();
	      this.port = socket.getPort();
	      m_controlThread = new DebugControlConnectionThread(socket, this);
	      m_controlThread.start();
	      executeStartupCommands();
	      m_controlThread.sendMessage("getsettings");

	      m_controlThread.sendMessage("[out-network");
	      //m_controlThread.sendMessage("[out-network-true");
	      String networkTracePortStr = m_controlThread.getMessage();
	      int networkTracePort = Integer.parseInt(networkTracePortStr);
	      if (LOG.isDebugEnabled()) LOG.debug("Received network trace port [" + networkTracePort + "]");
	      
	      try
	      {
	        INetworkOutputConfig config = new INetworkOutputConfig()
	        {
		          @Override
		          public boolean isNetOutputEnabled()
		          {
		            return m_settingsData.netOutEnabled;
		          }

				@Override
				public boolean isGzipEnabled() {
					return m_settingsData.gzipEnabled;
				}
	        };
	        	        
	        m_networkTraceThread2 = new NetworkDataReceiverThread2(
	        							m_remoteAddress,
	        							networkTracePort, 
	        							config
	        							);
	        m_networkTraceThread2.start();
		      setConnectState(ConnectState.CONNECTED);
		      setConnectionStatusMsg(DefaultFactory.getFactory().getMessages().getConnected());
	        
	      } catch (IOException ex)
	      {
	    	  m_traceEvents.add(
	    			  	TraceFactory.createExceptionTraceEvent(
	    			  			org.headlessintrace.rcp.ClientStrings.TRACE_CREATION_ERROR, 
	    			  			ex, 
	    			  			m_remoteAddress, 
	    			  			networkTracePortStr));
	      }
	      
	    } else
	    {
	      setConnectState(ConnectState.DISCONNECTED_ERR);
	    }
	}
431175
private function acceptConnection(): void
    {
        $clientSocket = @stream_socket_accept($this->serverSocket);

        if (false !== $clientSocket) {
            stream_set_blocking($clientSocket, false);

            $connection = new StreamSocketConnection($clientSocket);

            $id = spl_object_hash($connection);

            $this->clientSockets[$id] = $clientSocket;
            $this->connections[$id]   = $connection;
        }
    }