Interact with the socket. This will send all keyboard input to the
        socket and input from the socket to the console until an EOF occurs.
15491
def interact(self):
        

        sockets = [sys.stdin, self.channel]
        while True:
            ready = select.select(sockets, [], [])[0]

            if sys.stdin in ready:
                line = sys.stdin.readline().encode('latin1')
                if not line:
                    break
                self.write(line)

            if self.channel in ready:
                self.read(1, echo=True)
73361
public void run() {

		try {
			while (true) {
				//server thread blocks until a client connects
				Socket socket = server.accept();

				System.out.println(new LogEntry("client (" + socket.getInetAddress().getHostAddress() + ") attempts to connect..."));
				Connection c = establishConnection(socket);
				updateConnectedClients(c);
			}
		} catch (IOException ioe) {
			System.out.println(new LogEntry("server forced to stop with message " + ioe.getClass().getName() + ' ' + ioe.getMessage()));
		} catch (Throwable t) {
			System.out.println(new LogEntry(Level.CRITICAL, "server forced to stop with message " + t.getClass().getName() + ' ' + t.getMessage(), t));
		}
	}
952126
@Override
	public void run() {

		// Read buffer
		ByteBuffer readBuffer = ByteBuffer.allocate(Math.min(maxPacketSize, 1024 * 1024));
		byte[] readArray = readBuffer.array();

		// Processing variables
		Iterator<SelectionKey> keys;
		SocketChannel channel;
		SelectionKey key;

		byte[] bytes;
		byte[] remaining;
		int processed;
		int pos;

		// Loop
		while (true) {

			// Waiting for sockets
			int n;
			try {
				n = selector.select(3000);
			} catch (NullPointerException nullPointer) {
				continue;
			} catch (Exception anyError) {
				break;
			}
			if (n < 1) {
				continue;
			}
			keys = selector.selectedKeys().iterator();
			while (keys.hasNext()) {
				key = keys.next();
				if (key == null) {
					continue;
				}
				if (!key.isValid()) {
					keys.remove();
					continue;
				}
				if (key.isAcceptable()) {

					// Accept channel
					try {

						// Register socket
						channel = serverChannel.accept();
						channel.configureBlocking(false);

						channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
						channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
						channel.setOption(StandardSocketOptions.SO_LINGER, -1);

						channel.register(selector, SelectionKey.OP_READ);

						// Debug
						if (debug) {
							logger.info("Client channel opened from " + channel.getRemoteAddress() + ".");
						}

					} catch (Exception cause) {
						close(key, cause);
					} finally {
						keys.remove();
					}

				} else if (key.isReadable()) {
					try {

						// Read bytes into the read buffer
						channel = (SocketChannel) key.channel();
						readBuffer.clear();
						n = channel.read(readBuffer);
						if (n < 0) {
							throw new EOFException();
						}
						if (n == 0) {
							keys.remove();
							continue;
						}

						// Debug
						if (debug) {
							logger.info(n + " bytes received from " + channel.getRemoteAddress() + ".");
						}

						// Get the incoming bytes
						bytes = new byte[n];
						System.arraycopy(readArray, 0, bytes, 0, n);

						// Add remaining bytes
						remaining = (byte[]) key.attachment();
						if (remaining != null) {
							byte[] tmp = new byte[remaining.length + bytes.length];
							System.arraycopy(remaining, 0, tmp, 0, remaining.length);
							System.arraycopy(bytes, 0, tmp, remaining.length, bytes.length);
							bytes = tmp;
							key.attach(null);
						}

						// Split data
						pos = 0;
						while ((processed = processPacket(bytes, pos)) > 0) {
							pos += processed;
						}

						// Has remaining?
						if (pos < bytes.length) {
							if (pos == 0) {
								remaining = bytes;
							} else {
								remaining = new byte[bytes.length - pos];
								System.arraycopy(bytes, pos, remaining, 0, remaining.length);
							}
							key.attach(remaining);
						}

					} catch (EOFException eof) {

						// Peer closed
						close(key, null);

					} catch (Exception cause) {
						close(key, cause);
					} finally {
						keys.remove();
					}
				}
			}
		}
	}
451637
public synchronized void run(){	
		while (true){
			try {
				if (incoming == null) {
		            wait();	            
		        }
				
				System.out.println("Socket opening ...");
				BufferedReader in = new BufferedReader(new InputStreamReader(
						incoming.getInputStream(), "UTF-8"));				
				//PrintStream out = (PrintStream) incoming.getOutputStream();
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
						incoming.getOutputStream(), "UTF-8"));
				
				String content = "";
				
				while (true){				
					int ch = in.read();
					if (ch == 0) //end of string
						break;
					
					content += (char) ch;
				}
				
				//System.out.println(content);
				String tagged = textpro.process(content);
				//Thread.sleep(4000);
				
				out.write(tagged.trim());
				out.write((char)0);
				out.flush();
			}
			catch (InterruptedIOException e){
				System.out.println("The conection is interrupted");	
			}
			catch (Exception e){
				System.out.println(e);
				e.printStackTrace();
			}
			
			//update pool
			//go back in wait queue if there is fewer than max
			this.setSocket(null);
			Vector<Session> pool = TaggingService.pool;
			synchronized (pool) {
				if (pool.size() >= TaggingService.maxNSession){
					/* too many threads, exit this one*/
					return;
				}
				else {				
					pool.addElement(this);
				}
			}
		}
	}
714827
def send_keys(self, keyString):
        
        assert type(keyString) is str
        self.mediator.interface.begin_send()
        try:
            self.mediator.send_string(keyString)
        finally:
            self.mediator.interface.finish_send()
250060
def interact(self,
	            msg='SHUTIT PAUSE POINT',
	            shutit_pexpect_child=None,
	            print_input=True,
	            level=1,
	            resize=True,
	            color='32',
	            default_msg=None,
	            wait=-1):
		""""""
		shutit_global.shutit_global_object.yield_to_draw()
		self.pause_point(msg=msg,
		                 shutit_pexpect_child=shutit_pexpect_child,
		                 print_input=print_input,
		                 level=level,
		                 resize=resize,
		                 color=color,
		                 default_msg=default_msg,
		                 interact=True,
		                 wait=wait)
224085
def on_connect(self, connection):
        ""
        self._stream = connection._reader
        self._buffer = SocketBuffer(self._stream, self._read_size)
        if connection.decode_responses:
            self.encoding = connection.encoding
223164
def _process_stdin(self):
        
        with nonblocking(sys.stdin.fileno()):
            data = self._stdin_reader.read()

        # Send input in chunks of 4k.
        step = 4056
        for i in range(0, len(data), step):
            self._send_packet({
                'cmd': 'in',
                'data': data[i:i + step],
            })
861295
public void run() {
		byte[] buffer = new byte[80];
		byte[] message;
		int count = 0;

		while (!closed && count >= 0) {
			try {
				//statement blocks
				count = stdIn.read(buffer);
			}
			catch (IOException ioe) {
				close();
			}
			if (count > 0) {
				message = new byte[count];
				System.arraycopy(buffer, 0, message, 0, count);
				if (!closed) {
					transceiver.transmit(message);
				}
				else {
					try {
						stdOut.write(("dialog closed: unable to transmit '" + new String(message).trim() + "'...").getBytes());
					}
					catch (IOException ioe) {
						//...
					}
				}
			}
		}
	}
719303
function _keyboard_interactive_process()
    {
        $responses = func_get_args();

        if (strlen($this->last_interactive_response)) {
            $response = $this->last_interactive_response;
        } else {
            $orig = $response = $this->_get_binary_packet();
            if ($response === false) {
                user_error('Connection closed by server');
                return false;
            }
        }

        if (!strlen($response)) {
            return false;
        }
        extract(unpack('Ctype', $this->_string_shift($response, 1)));

        switch ($type) {
            case NET_SSH2_MSG_USERAUTH_INFO_REQUEST:
                if (strlen($response) < 4) {
                    return false;
                }
                extract(unpack('Nlength', $this->_string_shift($response, 4)));
                $this->_string_shift($response, $length); // name; may be empty
                if (strlen($response) < 4) {
                    return false;
                }
                extract(unpack('Nlength', $this->_string_shift($response, 4)));
                $this->_string_shift($response, $length); // instruction; may be empty
                if (strlen($response) < 4) {
                    return false;
                }
                extract(unpack('Nlength', $this->_string_shift($response, 4)));
                $this->_string_shift($response, $length); // language tag; may be empty
                if (strlen($response) < 4) {
                    return false;
                }
                extract(unpack('Nnum_prompts', $this->_string_shift($response, 4)));

                for ($i = 0; $i < count($responses); $i++) {
                    if (is_array($responses[$i])) {
                        foreach ($responses[$i] as $key => $value) {
                            $this->keyboard_requests_responses[$key] = $value;
                        }
                        unset($responses[$i]);
                    }
                }
                $responses = array_values($responses);

                if (isset($this->keyboard_requests_responses)) {
                    for ($i = 0; $i < $num_prompts; $i++) {
                        if (strlen($response) < 4) {
                            return false;
                        }
                        extract(unpack('Nlength', $this->_string_shift($response, 4)));
                        // prompt - ie. "Password: "; must not be empty
                        $prompt = $this->_string_shift($response, $length);
                        //$echo = $this->_string_shift($response) != chr(0);
                        foreach ($this->keyboard_requests_responses as $key => $value) {
                            if (substr($prompt, 0, strlen($key)) == $key) {
                                $responses[] = $value;
                                break;
                            }
                        }
                    }
                }

                // see http://tools.ietf.org/html/rfc4256#section-3.2
                if (strlen($this->last_interactive_response)) {
                    $this->last_interactive_response = '';
                } elseif (defined('NET_SSH2_LOGGING')) {
                    $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
                        'UNKNOWN',
                        'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
                        $this->message_number_log[count($this->message_number_log) - 1]
                    );
                }

                if (!count($responses) && $num_prompts) {
                    $this->last_interactive_response = $orig;
                    return false;
                }

                /*
                   After obtaining the requested information from the user, the client
                   MUST respond with an SSH_MSG_USERAUTH_INFO_RESPONSE message.
                */
                // see http://tools.ietf.org/html/rfc4256#section-3.4
                $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses));
                for ($i = 0; $i < count($responses); $i++) {
                    $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]);
                    $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer');
                }

                if (!$this->_send_binary_packet($packet, $logged)) {
                    return false;
                }

                if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) {
                    $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
                        'UNKNOWN',
                        'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE',
                        $this->message_number_log[count($this->message_number_log) - 1]
                    );
                }

                /*
                   After receiving the response, the server MUST send either an
                   SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, or another
                   SSH_MSG_USERAUTH_INFO_REQUEST message.
                */
                // maybe phpseclib should force close the connection after x request / responses?  unless something like that is done
                // there could be an infinite loop of request / responses.
                return $this->_keyboard_interactive_process();
            case NET_SSH2_MSG_USERAUTH_SUCCESS:
                return true;
            case NET_SSH2_MSG_USERAUTH_FAILURE:
                return false;
        }

        return false;
    }
1354829
private void waitForInputChannelsToBeClosed() throws IOException, InterruptedException {
		// Wait for disconnection of all output gates
		while (true) {

			// Make sure, we leave this method with an InterruptedException when the task has been canceled
			if (this.executionObserver.isCanceled()) {
				throw new InterruptedException();
			}

			boolean allClosed = true;
			for (int i = 0; i < getNumberOfInputGates(); i++) {
				final InputGate<? extends IOReadableWritable> eig = this.inputGates.get(i);
				if (!eig.isClosed()) {
					allClosed = false;
				}
			}

			if (allClosed) {
				break;
			}
			else {
				Thread.sleep(SLEEPINTERVAL);
			}
		}
	}
146782
def enter(self):
        """"""
        self._communication.send(StartRequest,
                                 self._communication.left_end_needle,
                                 self._communication.right_end_needle)
243706
async def _run_socket(self):
        
        try:
            while True:
                message = await ZMQUtils.recv(self._socket)
                msg_class = message.__msgtype__
                if msg_class in self._handlers_registered:
                    # If a handler is registered, give the message to it
                    self._loop.create_task(self._handlers_registered[msg_class](message))
                elif msg_class in self._transactions:
                    # If there are transaction associated, check if the key is ok
                    _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class]
                    key = get_key(message)
                    if key in self._transactions[msg_class]:
                        # key exists; call all the coroutines
                        for args, kwargs in self._transactions[msg_class][key]:
                            self._loop.create_task(coroutine_recv(message, *args, **kwargs))
                        # remove all transaction parts
                        for key2 in responsible:
                            del self._transactions[key2][key]
                    else:
                        # key does not exist
                        raise Exception("Received message %s for an unknown transaction %s", msg_class, key)
                else:
                    raise Exception("Received unknown message %s", msg_class)
        except asyncio.CancelledError:
            return
        except KeyboardInterrupt:
            return
465665
def run(self):
        
        while True:
            req = self.socket.recv_json()

            try:
                answer = self.handle_request(req)
                self.socket.send(json.dumps(answer))

            except (AttributeError, TypeError) as e:
                self.socket.send_json({'error': str(e)})
314541
def on_open(self):
        
        def event_loop():
            logger.debug(pformat(self.query.request))
            self.send(json.dumps(self.query.request))
            while not self.event.is_set():
                #print('Waiting around on the socket: %s' % self.gettimeout())
                self.event.wait(self.gettimeout())
                
            logger.debug('Event loop terminating.')
    
        self.thread = threading.Thread(
            target=event_loop)
        self.thread.setDaemon(True)
        self.thread.start()
303886
function() {
		    //io = socket(process.env.PORT || process.env.NODE_PORT || 3333);
        io = socket(http);

		    io.on('connection', function(socket){
            console.log('connection happened');
			      //Logic for handeling a new connection here.
			      //ie. registering a user or something similar.

			      //The new connection can send commands.
			      socket.on('keydown', function(data) {
				        var index = keysToPress.indexOf(data.key);
				        if(index === -1) {
					          keysToPress.push(data.key);
				        }
			      });

			      socket.on('keyup', function(data) {
				        var index = keysToPress.indexOf(data.key);
				        if(index !== -1) {
					          keysToPress.splice(index, 1);
				        }
			      });

			      socket.on('restart', function(data) {
				        gameboy_instance.loadROM(rom);
			      });

		    });
	  }
890616
def listen(self, listenip="", listenport=DEF_TFTP_PORT,
               timeout=SOCK_TIMEOUT):
        """"""
        tftp_factory = TftpPacketFactory()

        # Don't use new 2.5 ternary operator yet
        # listenip = listenip if listenip else '0.0.0.0'
        if not listenip: listenip = '0.0.0.0'
        log.info("Server requested on ip %s, port %s" % (listenip, listenport))
        try:
            # FIXME - sockets should be non-blocking
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.bind((listenip, listenport))
            _, self.listenport = self.sock.getsockname()
        except socket.error as err:
            # Reraise it for now.
            raise err

        self.is_running.set()

        log.info("Starting receive loop...")
        while True:
            log.debug("shutdown_immediately is %s" % self.shutdown_immediately)
            log.debug("shutdown_gracefully is %s" % self.shutdown_gracefully)
            if self.shutdown_immediately:
                log.warning("Shutting down now. Session count: %d" %
                         len(self.sessions))
                self.sock.close()
                for key in self.sessions:
                    self.sessions[key].end()
                self.sessions = []
                break

            elif self.shutdown_gracefully:
                if not self.sessions:
                    log.warning("In graceful shutdown mode and all "
                             "sessions complete.")
                    self.sock.close()
                    break

            # Build the inputlist array of sockets to select() on.
            inputlist = []
            inputlist.append(self.sock)
            for key in self.sessions:
                inputlist.append(self.sessions[key].sock)

            # Block until some socket has input on it.
            log.debug("Performing select on this inputlist: %s", inputlist)
            try:
                readyinput, readyoutput, readyspecial = \
                        select.select(inputlist, [], [], SOCK_TIMEOUT)
            except select.error as err:
                if err[0] == EINTR:
                    # Interrupted system call
                    log.debug("Interrupted syscall, retrying")
                    continue
                else:
                    raise

            deletion_list = []

            # Handle the available data, if any. Maybe we timed-out.
            for readysock in readyinput:
                # Is the traffic on the main server socket? ie. new session?
                if readysock == self.sock:
                    log.debug("Data ready on our main socket")
                    buffer, (raddress, rport) = self.sock.recvfrom(MAX_BLKSIZE)

                    log.debug("Read %d bytes", len(buffer))

                    if self.shutdown_gracefully:
                        log.warning("Discarding data on main port, "
                                 "in graceful shutdown mode")
                        continue

                    # Forge a session key based on the client's IP and port,
                    # which should safely work through NAT.
                    key = "%s:%s" % (raddress, rport)

                    if not key in self.sessions:
                        log.debug("Creating new server context for "
                                     "session key = %s" % key)
                        self.sessions[key] = TftpContextServer(raddress,
                                                               rport,
                                                               timeout,
                                                               self.root,
                                                               self.dyn_file_func,
                                                               self.upload_open)
                        try:
                            self.sessions[key].start(buffer)
                        except TftpException as err:
                            deletion_list.append(key)
                            log.error("Fatal exception thrown from "
                                      "session %s: %s" % (key, str(err)))
                    else:
                        log.warning("received traffic on main socket for "
                                 "existing session??")
                    log.info("Currently handling these sessions:")
                    for session_key, session in list(self.sessions.items()):
                        log.info("    %s" % session)

                else:
                    # Must find the owner of this traffic.
                    for key in self.sessions:
                        if readysock == self.sessions[key].sock:
                            log.debug("Matched input to session key %s"
                                % key)
                            try:
                                self.sessions[key].cycle()
                                if self.sessions[key].state == None:
                                    log.info("Successful transfer.")
                                    deletion_list.append(key)
                            except TftpException as err:
                                deletion_list.append(key)
                                log.error("Fatal exception thrown from "
                                          "session %s: %s"
                                          % (key, str(err)))
                            # Break out of for loop since we found the correct
                            # session.
                            break
                    else:
                        log.error("Can't find the owner for this packet. "
                                  "Discarding.")

            log.debug("Looping on all sessions to check for timeouts")
            now = time.time()
            for key in self.sessions:
                try:
                    self.sessions[key].checkTimeout(now)
                except TftpTimeout as err:
                    log.error(str(err))
                    self.sessions[key].retry_count += 1
                    if self.sessions[key].retry_count >= TIMEOUT_RETRIES:
                        log.debug("hit max retries on %s, giving up" %
                            self.sessions[key])
                        deletion_list.append(key)
                    else:
                        log.debug("resending on session %s" % self.sessions[key])
                        self.sessions[key].state.resendLast()

            log.debug("Iterating deletion list.")
            for key in deletion_list:
                log.info('')
                log.info("Session %s complete" % key)
                if key in self.sessions:
                    log.debug("Gathering up metrics from session before deleting")
                    self.sessions[key].end()
                    metrics = self.sessions[key].metrics
                    if metrics.duration == 0:
                        log.info("Duration too short, rate undetermined")
                    else:
                        log.info("Transferred %d bytes in %.2f seconds"
                            % (metrics.bytes, metrics.duration))
                        log.info("Average rate: %.2f kbps" % metrics.kbps)
                    log.info("%.2f bytes in resent data" % metrics.resent_bytes)
                    log.info("%d duplicate packets" % metrics.dupcount)
                    log.debug("Deleting session %s" % key)
                    del self.sessions[key]
                    log.debug("Session list is now %s" % self.sessions)
                else:
                    log.warning(
                        "Strange, session %s is not on the deletion list" % key)

        self.is_running.clear()

        log.debug("server returning from while loop")
        self.shutdown_gracefully = self.shutdown_immediately = False