Connects the socket and spawns the send/receive loops.
542616
def connect(self):
        
        jobs = []
        self._socket.connect((self.host, self.port))
        try:
            jobs = [spawn(self._recv_loop), spawn(self._send_loop)]
            joinall(jobs)
        finally:
            killall(jobs)
314003
def _init_listen_socket(self):
        
        self.debug("()")
        self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._listen_socket.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_REUSEADDR,
            1
        )
        self._listen_socket.bind((self._listen_ip, self._listen_port))
        self._listening.append(self._listen_socket)
567708
private function connect():void
    {

        socket_connect($this->socket, $this->host, $this->port) or $this->error();

    }
1051962
def initialize(self, timeouts):
        

        # Bind or connect to address
        if self.bind is True:
            self.socket.bind(self.address)
        else:
            self.socket.connect(self.address)

        # Set send and recv timeouts
        self._set_timeouts(timeouts)
1188738
def _do_connect(self):
        """"""
        _, self._protocol = yield from self._loop.create_connection(
            lambda: SnapcastProtocol(self._callbacks), self._host, self._port)
241060
def _connect(self):
        """"""
        assert get_thread_ident() == self.ioloop_thread_id
        if self._stream:
            self._logger.warn('Disconnecting existing connection to {0!r} '
                              'to create a new connection')
            self._disconnect()
            yield self._disconnected.until_set()

        stream = None
        try:
            host, port = self._bindaddr
            stream = self._stream = yield self._tcp_client.connect(
                host, port, max_buffer_size=self.MAX_MSG_SIZE)
            stream.set_close_callback(partial(self._stream_closed_callback,
                                              stream))
            # our message packets are small, don't delay sending them.
            stream.set_nodelay(True)
            stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE
            self._logger.debug('Connected to {0} with client addr {1}'
                               .format(self.bind_address_string,
                                       address_to_string(stream.socket.getsockname())))
            if self._connect_failures >= 5:
                self._logger.warn("Reconnected to {0}"
                                  .format(self.bind_address_string))
            self._connect_failures = 0
        except Exception, e:
            if self._connect_failures % 5 == 0:
                # warn on every fifth failure

                # TODO (NM 2015-03-04) This can get a bit verbose, and typically we have
                # other mechanisms for tracking failed connections. Consider doing some
                # kind of exponential backoff starting at 5 times the reconnect time up to
                # once per 5 minutes
                self._logger.debug("Failed to connect to {0!r}: {1}"
                                  .format(self._bindaddr, e))
            self._connect_failures += 1
            stream = None
            yield gen.moment
            # TODO some kind of error rate limiting?

            if self._stream:
                # Can't use _disconnect() and wait on self._disconnected, since
                # exception may have been raised before _stream_closed_callback
                # was attached to the iostream.
                self._logger.debug('stream was set even though connecting failed')
                self._stream.close()
                self._disconnected.set()

        if stream:
            self._disconnected.clear()
            self._connected.set()
            self.last_connect_time = self.ioloop.time()
            try:
                self.notify_connected(True)
            except Exception:
                self._logger.exception("Notify connect failed. Disconnecting.")
                self._disconnect()
903596
void connect(SocketAddress socketAddress, boolean useSSL) {
        ChannelFactory channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());

        ChannelPipeline clientPipeline = NettyChannelPipeline.newPipeline(connection);
        SslHandler sslHandler = null;

        if (useSSL) {
            sslHandler = getClientSSLHandler();
            clientPipeline.addFirst("ssl", sslHandler);
        }

        bootstrap = new ClientBootstrap(channelFactory);
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setPipeline(clientPipeline);

        /*
         * The connection future and the connection itself aren't perfectly
         * synchronized so we have to wait for both to acknowledge that the
         * connection has been made
         */
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        ConnectionStateListener connectedListener = new ConnectionStateListener() {
            @Override
            public void onConnectionConnected() {
                connectedLatch.countDown();
            }

            @Override
            public void onConnectionClosing() {
            }

            @Override
            public void onConnectionClosed() {
            }
        };

        connection.addConnectionStateListener(connectedListener);

        try {
            /* Perform connection */
            ChannelFuture future = bootstrap.connect(socketAddress);

            log.debug("connecting");

            future.await();

            if (future.isSuccess()) {
                /* This await should be very brief */
                connectedLatch.await();

                log.debug("connected successfully");

                if (useSSL) {
                    doSSLHandshake(sslHandler);
                }

                connected = true;
            } else {
                log.debug("connection failed");
                throw new ConnectionException(future.getCause());
            }
        } catch (InterruptedException e) {
            throw new ConnectionException("Interrupted while connecting");
        } finally {
            connection.removeConnectionStateListener(connectedListener);
        }
    }
412051
public void connect() {
        try {
            ws.setPingInterval(pingInterval);
            ws.connect();
        } catch (WebSocketException e){
            e.printStackTrace();
            if(onErrorListener != null) {
                onErrorListener.onError(e);
            }
            if(tryReconnection) {
                if (timer == null) {
                    // this is to handle reconnection first time
                    if (lastPongAt == 0) {
                        lastPongAt = 1;
                    }
                    timer = new Timer();
                    timer.scheduleAtFixedRate(getTask(), 0, pongCheckInterval);
                }
            }
        }
    }
1177429
private function connect()
    {
        if (!$this->socket->isOpened()) {
            $this->socket->open();

            if ($this->secret) {
                $this->socket->send(join(Driver::SEP, ['A', 1, Driver::encode($this->secret)]).Driver::EOL);
            }
        }
    }
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();
					}
				}
			}
		}
	}
1241424
function connection(socket){
	this.socket = socket;
	if (!!this.options.encoding) socket.setEncoding(this.options.encoding);
	socket.on('data', this.emit.bind(this, 'data'));
	this.emit('connection', socket);
}
964107
public void connect() throws ConnectException {
        try {
            connectToWebSocket();
            setWebSocketListener();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("Interrupted while connecting via WebSocket protocol");
        }
    }
1000006
public void run() {
      /**
        * Ensure we start fresh.
        */
    getLogger().debug("performing socket cleanup prior to entering loop for {}",  name);
    closeServerSocket();
    closeAllAcceptedSockets();
    getLogger().debug("socket cleanup complete for {}", name);       
    active = true;

    // start the server socket
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      getLogger().error(
        "error starting SocketReceiver (" + this.getName()
        + "), receiver did not start", e);
      active = false;
      doShutdown();

      return;
    }

    Socket socket = null;

    try {
      getLogger().debug("in run-about to enter while isactiveloop");

      active = true;

      while (!rThread.isInterrupted()) {
        // if we have a socket, start watching it
        if (socket != null) {
          getLogger().debug("socket not null - creating and starting socketnode");
          socketList.add(socket);

          XMLSocketNode node = new XMLSocketNode(decoder, socket, this);
          node.setLoggerRepository(this.repository);
          new Thread(node).start();
          socket = null;
        }

        getLogger().debug("waiting to accept socket");

        // wait for a socket to open, then loop to start it
        socket = serverSocket.accept();
        getLogger().debug("accepted socket");
      }

      // socket not watched because we a no longer running
      // so close it now.
      if (socket != null) {
        socket.close();
      }
    } catch (Exception e) {
      getLogger().warn(
        "socket server disconnected, stopping");
    }
  }
163247
def run(self):
        

        self.ws = self.connect()
        while True:
            try:
                data = json.loads(self.ws.recv())
                self.handle(data)
            except json.decoder.JSONDecodeError as e:
                logger.fatal("No data on socket...")
405048
def _send(self, data):
        """"""
        if not self._sock:
            self.connect()
        self._do_send(data)
1297421
def connect(self):
        """"""
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(self._connect_timeout)
        SocketError.wrap(self._socket.connect, (self.host, self.port))
        self._socket.settimeout(None)
        self._socket_file = self._socket.makefile('rb')
705779
public void run() {

	InputStream in   = null;
	OutputStream out = null;

	try {
	    in  = socket.getInputStream();
	    out = socket.getOutputStream();

	    try {

		String line;
		line = readLine(in);

		if (DEBUG_ON) debug("header: " + line);

		if (line.startsWith("GET") &&
		    (options & GassServer.READ_ENABLE) != 0) {

		    // copy to client

		    String path =
			line.substring(4, line.indexOf(' ', 4) );

		    do {
			line = readLine(in);
			if (DEBUG_ON) debug("header (get): " + line);
		    } while ( (line.length() != 0)
			      && (line.charAt(0) != '\r')
			      && (line.charAt(0) != '\n') );

		    transfer(out, path);

		} else if (line.startsWith("PUT") &&
			   ( ((options & GassServer.WRITE_ENABLE) != 0) ||
			     ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) {

		    // copy from client

		    String path =
			line.substring(4, line.indexOf(' ', 4) );

		    transfer(in, path, false, out);

		    writeln(out, OKHEADER);

		} else if (line.startsWith("POST") &&
			   ( ((options & GassServer.WRITE_ENABLE) != 0) ||
			     ((options & GassServer.STDOUT_ENABLE) != 0) ||
			     ((options & GassServer.STDERR_ENABLE) != 0) ||
			     ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) {
		    // append from client

		    int index = line.indexOf('?') + 1;
		    String path =
			line.substring(index, line.indexOf(' ', index) );

		    transfer(in, path, true, out);

		    writeln(out, OKHEADER);

		} else {
		    writeln(out, "HTTP/1.1 400 Bad Request" + CRLF);
		}

	    } catch (FileNotFoundException ex) {
		logger.debug("FileNotFoundException occured: " + ex.getMessage(), ex);

		StringBuffer buf = new StringBuffer(HEADER404)
		    .append(CONNECTION_CLOSE)
		    .append(SERVER)
		    .append(CONTENT_HTML)
		    .append(CONTENT_LENGTH).append(" ").append(MSG404.length())
		    .append(CRLF).append(CRLF)
		    .append(MSG404);

		out.write(buf.toString().getBytes());
		out.flush();
	    } catch (AuthorizationException ex) {
		logger.debug("Exception occured: Authorization failed");
		writeln(out, "HTTP/1.1 401 Authorization Failed" + CRLF);
	    } catch (Exception ex) {
		logger.debug("Exception occured: " + ex.getMessage(), ex);
		writeln(out, "HTTP/1.1 400 " + ex.getMessage() + CRLF);
	    }
	} catch (IOException e) {
	    logger.error("Error writing response: " + e.getMessage(), e);
	} finally {
	    try {
		socket.close();
	    } catch (IOException e) {}
	}
    }