Listen on the server socket for a client, start another thread to
keep listening on the server socket, then deal with the client.
422363
public void run() {

	BufferedWriter out = null;

	try {
	    out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
	    try {

		CallbackResponse hd =
		    new CallbackResponse( socket.getInputStream() );

		if (hd.protocolVersion != GRAMProtocol.GRAM_PROTOCOL_VERSION) {
		    throw new Exception("Gram callback protocol version mismatch");
		}

		GramJob job = handler.getJob( hd.jobManagerUrl );
		if (job == null) {
		    throw new Exception("Not registered with this handler: " +
					hd.jobManagerUrl);
		}

		job.setError( hd.failureCode );
		// the exit code needs to be set before the
		// status, since setStatus triggers a listener
		// notification
		job.setExitCode ( hd.exitCode );
		job.setStatus( hd.status );

		if (job.getStatus() == GramJob.STATUS_DONE ||
		    job.getStatus() == GramJob.STATUS_FAILED) {
		    handler.unregisterJob(job);
		}

		try {
		    out.write(GRAMProtocol.OKReply());
		    out.flush();
		} catch(IOException ignoreE) {
		    logger.debug("Ignoring IOException");
		}

	    } catch(AuthorizationException ex) {
		logger.debug("Authorization failed", ex);
		out.write(GRAMProtocol.ErrorReply(401, "Authorization Failed"));
		out.flush();
	    } catch (Exception ex) {
		logger.debug("General error", ex);
		out.write(GRAMProtocol.ErrorReply(400, ex.getMessage()));
		out.flush();
	    }
	} catch (IOException e) {
	    logger.debug("IO Error", e);
	} finally {
	    try {
		socket.close();
	    } catch (IOException e) { }
	}
    }
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;
        }
    }
136130
public void start() throws IOException {
        myServerSocket = new ServerSocket();
        myServerSocket.bind((hostname != null) ? new InetSocketAddress(
                hostname, myPort) : new InetSocketAddress(myPort));

        myThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        final Socket finalAccept = myServerSocket.accept();
                        registerConnection(finalAccept);
                        finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                        final InputStream inputStream = finalAccept
                                .getInputStream();
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                OutputStream outputStream = null;
                                try {
                                    outputStream = finalAccept
                                            .getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory
                                            .create();
                                    HTTPSession session = new HTTPSession(
                                            tempFileManager, inputStream,
                                            outputStream, finalAccept
                                                    .getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client,
                                    // we throw our own SocketException
                                    // to break the "keep alive" loop above.
                                    if (!(e instanceof SocketException && "NanoHttpd Shutdown"
                                            .equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(outputStream);
                                    safeClose(inputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    } catch (IOException e) {
                    }
                } while (!myServerSocket.isClosed());
            }
        });
        myThread.setDaemon(true);
        myThread.setName("NanoHttpd Main Listener");
        myThread.start();
    }
206589
def serve(socket)
      header = read_header(socket)
      # not documented protocol?
      if header['probe'] == '1'
        write_header(socket, build_header)
      elsif check_header(header)
        write_header(socket, build_header)
        read_and_callback(socket)
        if header['persistent'] == '1'
          loop do
            read_and_callback(socket)
          end
        end
      else
        socket.close
        raise 'header check error'
      end
    end
99060
public void run() {
        try {
            mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost());
        } catch (Exception e) {
            Log.w(LOG_TAG, "Starting ServerSocket error: ", e);
        }

        while (mServer != null && Thread.currentThread() == mThread) {
            // Any uncaught exception will crash the system process
            try {
                Socket client = mServer.accept();
                if (mThreadPool != null) {
                    mThreadPool.submit(new ViewServerWorker(client));
                } else {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                Log.w(LOG_TAG, "Connection error: ", e);
            }
        }
    }
709375
public void run() {
        if(log.isDebugEnabled()) {
            log.debug("ListenerThread Starting.");
        }

        while(running) {
            try {
                Socket clientSocket = serverSocket.accept();

                WorkerThread worker = new WorkerThread(container, clientSocket);
                worker.start();

            } catch(SocketTimeoutException ste) {
                // Ignore. We receive one of these every second, when the accept()
                // method times out. This is done to give us the opportunity to break
                // out of the blocking accept() call in order to shut down cleanly.

            } catch(Exception e) {
                if(log.isErrorEnabled()) {
                    log.error("Error Accepting: " + e.toString(), e);
                }
            }
        }

		try {
			serverSocket.close();
			
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error("Error closing the server socket: " + e.toString(), e);
			}
		}
    }
239797
def _socket_connect(self):
        """"""
        self.usage_count = 0
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            s.connect((self._host, self._port))
            self.__stream = self.__backend.register_stream(s, **self.__kwargs)
            self.__stream.set_close_callback(self._socket_close)
            self.__alive = True
        except socket.error, error:
            raise InterfaceError(error)
614987
def run(self):
        
        listen_socket = self.create_socket(self.host, self.port)
        logger.info('Listening for telnet connections on %s port %r', self.host, self.port)

        try:
            while True:
                # Removed closed connections.
                self.connections = set([c for c in self.connections if not c.closed])

                # Ignore connections handling commands.
                connections = set([c for c in self.connections if not c.handling_command])

                # Wait for next event.
                read_list = (
                    [listen_socket, self._schedule_pipe[0]] +
                    [c.conn for c in connections])

                read, _, _ = select.select(read_list, [], [])

                for s in read:
                    # When the socket itself is ready, accept a new connection.
                    if s == listen_socket:
                        self._accept(listen_socket)

                    # If we receive something on our "call_from_executor" pipe, process
                    # these callbacks in a thread safe way.
                    elif s == self._schedule_pipe[0]:
                        self._process_callbacks()

                    # Handle incoming data on socket.
                    else:
                        self._handle_incoming_data(s)
        finally:
            listen_socket.close()
1258841
protected void runEchoService(ServerSocket serverSocket) {
    if (isRunning(serverSocket)) {

      echoService = newExecutorService();

      echoService.submit(() -> {
        try {
          while (isRunning(serverSocket)) {
            Socket echoClient = serverSocket.accept();

            getLogger().info(() -> String.format("EchoClient connected from [%s]",
              echoClient.getRemoteSocketAddress()));

            echoService.submit(() -> {
              sendResponse(echoClient, receiveMessage(echoClient));
              close(echoClient);
            });
          }
        }
        catch (IOException cause) {
          if (isRunning(serverSocket)) {
            getLogger().warning(() -> String.format("An IO error occurred while listening for EchoClients:%n%s",
              ThrowableUtils.getStackTrace(cause)));
          }
        }
      });

      getLogger().info(() -> String.format("EchoServer running on port [%d]", getPort()));
    }
  }
1066213
def handle(self):
        
        # self.request is the TCP socket connected to the client
        try:
            while not self.server._shutdown_request_event.is_set():
                try:
                    data = self.request.recv(8192)
                    if not data:
                        break
                    if self.debug:
                        self.log.debug("RECV: %r" % data)
                    self.buffer.append(data)

                    for frame in self.buffer:
                        self.log.debug("Processing frame: %s" % frame)
                        self.engine.process_frame(frame)
                        if not self.engine.connected:
                            raise ClientDisconnected()
                except socket.timeout:  # pragma: no cover
                    pass
        except ClientDisconnected:
            self.log.debug("Client disconnected, discontinuing read loop.")
        except Exception as e:  # pragma: no cover
            self.log.error("Error receiving data (unbinding): %s" % e)
            self.engine.unbind()
            raise
219670
public void handleConnection(Socket socket)
        throws IOException
    {
        HttpConnection connection = createConnection(socket);
        
        try
        {
            if (_lowResourcePersistTimeMs>0 && isLowOnResources())
            {
                socket.setSoTimeout(_lowResourcePersistTimeMs);
                connection.setThrottled(true);
            }
            else
            {
                socket.setSoTimeout(getMaxIdleTimeMs());
                connection.setThrottled(false);
            }
            
        }
        catch(Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
        }

        connection.handle();
    }
141607
function listen() {
	let httpServer = require('http').createServer(router);
	httpServer.listen(port);
	Coralian.logger.log("Server started");
}
822392
def start_listener(self):
        ''''''
        if self.sock is not None:
            self.sock.close()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(('', self.asterix_settings.port))
        self.sock.setblocking(False)
        print("Started on port %u" % self.asterix_settings.port)
1080710
void handleDisconnected() throws IOException {
		synchronized (this.asyncMutex) {
			if (socket != null) {
				socket.close();
			}
			this.socket = new Socket(server, port);
			this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
			
			this.listenThread = new SocketThread(this.in, this, this.resultParser, this.daemon);
			this.listenThread.start();
			if (lastWatch != null) { // restore watch if we had one.
				this.syncCommand(lastWatch, WatchObject.class);
			}
		}
		
	}
190429
public function run()
    {
        $this->log("Server listening on {$this->host}:{$this->port}");
        $this->socket->listen($this->port, $this->host);
        $this->loop->run();
    }
992241
def start(self) -> None:
        
        self.stop()  # stop an existing thread
        self._thread = receiverThread(socket=self.sock, callbacks=self._callbacks)
        self._thread.start()
112
def start
      if(@sockets.size < 0)
        raise 'No sockets available for listening'
      elsif(!@runner.nil? && @runner.alive?)
        raise AlreadyRunning.new
      else
        @stop = false
        @runner = Thread.new{watch}
      end
    end