Initialize the ddp socket
972067
def _init_socket(self):
        """"""
        # destroy the connection if it already exists
        if self.ddpsocket:
            self.ddpsocket.remove_all_listeners('received_message')
            self.ddpsocket.remove_all_listeners('closed')
            self.ddpsocket.remove_all_listeners('opened')
            self.ddpsocket.close_connection()
            self.ddpsocket = None

        # create a ddp socket and subscribe to events
        self.ddpsocket = DDPSocket(self.url, self.debug)
        self.ddpsocket.on('received_message', self.received_message)
        self.ddpsocket.on('closed', self.closed)
        self.ddpsocket.on('opened', self.opened)
525613
function init(domainManager) {
    _domainManager = domainManager;
    if (!domainManager.hasDomain("webSocketTransport")) {
        domainManager.registerDomain("webSocketTransport", {major: 0, minor: 1});
    }
    
    domainManager.registerEvent(
        "webSocketTransport",
        "message",
        [
            {
                name: "msg",
                type: "string",
                description: "JSON message from client page"
            }
        ]
    );
    
    domainManager.registerCommand(
        "webSocketTransport",       // domain name
        "start",                    // command name
        _cmdStart,                  // command handler function
        false,                      // this command is synchronous in Node
        "Creates the WS server",
        [
            {
                name: "port",
                type: "number",
                description: "Port on which server needs to listen"
            }
        ],
        []
    );
    
    domainManager.registerCommand(
        "webSocketTransport",       // domain name
        "close",                    // command name
        _cmdClose,                  // command handler function
        false,                      // this command is synchronous in Node
        "Kills the websocket server",
        []
    );
}
539617
def initialize_connection(self):  # noqa: E501 pylint:disable=too-many-statements, too-many-branches
        """"""
        tries = self.tries

        if self.socket is not None:
            self.socket.close()
            self.socket = None

        # Make sure nobody is blocking.
        for callback in self._request_callbacks.values():
            callback['event'].set()

        self.app_namespaces = []
        self.destination_id = None
        self.session_id = None
        self._request_id = 0
        self._request_callbacks = {}
        self._open_channels = []

        self.connecting = True
        retry_log_fun = self.logger.error

        # Dict keeping track of individual retry delay for each named service
        retries = {}

        def mdns_backoff(service, retry):
            """Exponentional backoff for service name mdns lookups."""
            now = time.time()
            retry['next_retry'] = now + retry['delay']
            retry['delay'] = min(retry['delay']*2, 300)
            retries[service] = retry

        while not self.stop.is_set() and (tries is None or tries > 0):  # noqa: E501 pylint:disable=too-many-nested-blocks
            # Prune retries dict
            retries = {key: retries[key] for key in self.services if (
                key is not None and key in retries)}

            for service in self.services.copy():
                now = time.time()
                retry = retries.get(
                    service, {'delay': self.retry_wait, 'next_retry': now})
                # If we're connecting to a named service, check if it's time
                if service and now < retry['next_retry']:
                    continue
                try:
                    self.socket = new_socket()
                    self.socket.settimeout(self.timeout)
                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_CONNECTING,
                                         NetworkAddress(self.host, self.port)))
                    # Resolve the service name. If service is None, we're
                    # connecting directly to a host name or IP-address
                    if service:
                        host = None
                        port = None
                        service_info = get_info_from_service(service,
                                                             self.zconf)
                        host, port = get_host_from_service_info(service_info)
                        if host and port:
                            try:
                                self.fn = service_info.properties[b'fn']\
                                    .decode('utf-8')
                            except (AttributeError, KeyError, UnicodeError):
                                pass
                            self.logger.debug(
                                "[%s:%s] Resolved service %s to %s:%s",
                                self.fn or self.host, self.port, service, host,
                                port)
                            self.host = host
                            self.port = port
                        else:
                            self.logger.debug(
                                "[%s:%s] Failed to resolve service %s",
                                self.fn or self.host, self.port, service)
                            self._report_connection_status(
                                ConnectionStatus(
                                    CONNECTION_STATUS_FAILED_RESOLVE,
                                    NetworkAddress(service, None)))
                            mdns_backoff(service, retry)
                            # If zeroconf fails to receive the necessary data,
                            # try next service
                            continue

                    self.logger.debug("[%s:%s] Connecting to %s:%s",
                                      self.fn or self.host, self.port,
                                      self.host, self.port)
                    self.socket.connect((self.host, self.port))
                    self.socket = ssl.wrap_socket(self.socket)
                    self.connecting = False
                    self._force_recon = False
                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_CONNECTED,
                                         NetworkAddress(self.host, self.port)))
                    self.receiver_controller.update_status()
                    self.heartbeat_controller.ping()
                    self.heartbeat_controller.reset()

                    self.logger.debug("[%s:%s] Connected!",
                                      self.fn or self.host, self.port)
                    return
                except OSError as err:
                    self.connecting = True
                    if self.stop.is_set():
                        self.logger.error(
                            "[%s:%s] Failed to connect: %s. "
                            "aborting due to stop signal.",
                            self.fn or self.host, self.port, err)
                        raise ChromecastConnectionError("Failed to connect")

                    self._report_connection_status(
                        ConnectionStatus(CONNECTION_STATUS_FAILED,
                                         NetworkAddress(self.host, self.port)))
                    if service is not None:
                        retry_log_fun(
                            "[%s:%s] Failed to connect to service %s"
                            ", retrying in %.1fs",
                            self.fn or self.host, self.port,
                            service, retry['delay'])
                        mdns_backoff(service, retry)
                    else:
                        retry_log_fun(
                            "[%s:%s] Failed to connect, retrying in %.1fs",
                            self.fn or self.host, self.port, self.retry_wait)
                    retry_log_fun = self.logger.debug

            # Only sleep if we have another retry remaining
            if tries is None or tries > 1:
                self.logger.debug(
                    "[%s:%s] Not connected, sleeping for %.1fs. Services: %s",
                    self.fn or self.host, self.port,
                    self.retry_wait, self.services)
                time.sleep(self.retry_wait)

            if tries:
                tries -= 1

        self.stop.set()
        self.logger.error("[%s:%s] Failed to connect. No retries.",
                          self.fn or self.host, self.port)
        raise ChromecastConnectionError("Failed to connect")
65012
protected void initialize() throws IOException {
    // set service-level authorization security policy
    if (serviceAuthEnabled =
        getConf().getBoolean(
            ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
      PolicyProvider policyProvider =
        (PolicyProvider)(ReflectionUtils.newInstance(
            getConf().getClass(PolicyProvider.POLICY_PROVIDER_CONFIG,
                HDFSPolicyProvider.class, PolicyProvider.class),
            getConf()));
      SecurityUtil.setPolicy(new ConfiguredPolicy(getConf(), policyProvider));
    }

    // This is a check that the port is free
    // create a socket and bind to it, throw exception if port is busy
    // This has to be done before we are reading Namesystem not to waste time and fail fast
    NetUtils.isSocketBindable(getClientProtocolAddress(getConf()));
    NetUtils.isSocketBindable(getDNProtocolAddress(getConf()));
    NetUtils.isSocketBindable(getHttpServerAddress(getConf()));

    long serverVersion = ClientProtocol.versionID;
    this.clientProtocolMethodsFingerprint = ProtocolSignature
        .getMethodsSigFingerPrint(ClientProtocol.class, serverVersion);

    myMetrics = new NameNodeMetrics(getConf(), this);

    this.clusterName = getConf().get(FSConstants.DFS_CLUSTER_NAME);
    this.namesystem = new FSNamesystem(this, getConf());
    // HACK: from removal of FSNamesystem.getFSNamesystem().
    JspHelper.fsn = this.namesystem;

    this.startDNServer();
    startHttpServer(getConf());
  }
443053
def setup_domain_socket(location):

    '''
        
    '''

    clientsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    clientsocket.settimeout(timeout)
    clientsocket.connect(location)

    return clientsocket
923640
protected void createDDPClient() {
        try {
            if (mTrustManagers != null) {
                mDDP = new DDPClient(getServerHostname(), getServerPort(), mTrustManagers);
            } else {
                mDDP = new DDPClient(getServerHostname(), getServerPort(), mMeteorSsl);
            }
        } catch (URISyntaxException e) {
            log.error("Invalid Websocket URL connecting to " + getServerHostname()
                    + ":" + getServerPort());
        }
        getDDP().addObserver(this);
        mDDPState = DDPSTATE.NotLoggedIn;
    }
630956
def connect(ipAddr, port, password):
    """"""

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect((ipAddr, port))
    sock.settimeout(2)

    # Make sure it pongs.
    sock.send(b'd1:q4:pinge')
    data = sock.recv(BUFFER_SIZE)
    if not data.endswith(b'1:q4:ponge'):
        raise exceptions.NotACjdnsAdminSocket("Looks like %s:%d is to a non-cjdns socket.",
                                              (ipAddr, port))

    # Get the functions and make the object
    page = 0
    availableFunctions = {}
    while True:
        sock.send(bytearray(
            'd1:q24:Admin_availableFunctions4:argsd4:pagei%seee' % page,
            'utf-8'))
        data = sock.recv(BUFFER_SIZE)
        benc = bdecode(data)
        for func in benc['availableFunctions']:
            availableFunctions[func] = benc['availableFunctions'][func]
        if 'more' not in benc:
            break
        page = page+1

    funcArgs = {}
    funcOargs = {}

    for (i, func) in availableFunctions.items():
        items = func.items()

        # grab all the required args first
        # append all the optional args
        rargList = [arg for arg, atts in items if atts['required']]
        argList = rargList + [
            arg for arg, atts in items if not atts['required']]

        # for each optional arg setup a default value with
        # a type which will be ignored by the core.
        oargList = {}
        for (arg, atts) in items:
            if not atts['required']:
                oargList[arg] = (
                    "''" if func[arg]['type'] == 'Int'
                    else "")

        setattr(Session, i, _functionFabric(
            i, argList, oargList, password))

        funcArgs[i] = rargList
        funcOargs[i] = oargList

    session = Session(sock)

    kat = threading.Thread(target=_receiverThread, args=[session])
    kat.setDaemon(True)
    kat.start()

    # Check our password.
    ret = _callFunc(session, "ping", password, {})
    if 'error' in ret:
        raise exceptions.InvalidAdminPassword(ret.get("error"))

    session._functions = ""

    funcOargs_c = {}
    for func in funcOargs:
        funcOargs_c[func] = list([
            key + "=" + str(value) for (key, value) in funcOargs[func].items()
        ])

    for func in availableFunctions:
        session._functions += (
            func + "(" + ', '.join(funcArgs[func] + funcOargs_c[func]) + ")\n")

    return session
1274157
function (host, port, prefix, suffix, globalize, cacheDns, mock,
    globalTags, maxBufferSize, bufferFlushInterval, telegraf, sampleRate, protocol) {
  let options = host || {};
  const self = this;

  // Adding options below is DEPRECATED.  Use the options object instead.
  if (arguments.length > 1 || typeof(host) === 'string') {
    options = {
      host        : host,
      port        : port,
      prefix      : prefix,
      suffix      : suffix,
      globalize   : globalize,
      cacheDns    : cacheDns,
      mock        : mock === true,
      globalTags  : globalTags,
      maxBufferSize : maxBufferSize,
      bufferFlushInterval: bufferFlushInterval,
      telegraf    : telegraf,
      sampleRate  : sampleRate,
      protocol    : protocol
    };
  }

  const createSocket = function createSocket(instance, args) {
    let socket;
    let errMessage;

    if (args.protocol === 'tcp') {
      try {
        socket = net.connect(args.port, args.host);
        socket.setKeepAlive(true);
      } catch (e) {
        errMessage = `Could not establish connection to ${args.host}:${args.port}`;
        if (instance.errorHandler) {
          instance.errorHandler(new Error(errMessage));
        } else {
          console.log(errMessage);
        }
      }
    } else {
      socket = dgram.createSocket('udp4');
    }

    return socket;
  };

  // hidden global_tags option for backwards compatibility
  options.globalTags = options.globalTags || options.global_tags;

  this.protocol    = (options.protocol && options.protocol.toLowerCase());
  this.host        = options.host || process.env.DD_AGENT_HOST || 'localhost';
  this.port        = options.port || parseInt(process.env.DD_DOGSTATSD_PORT, 10) || 8125;
  this.prefix      = options.prefix || '';
  this.suffix      = options.suffix || '';
  this.socket      = options.isChild ? options.socket : createSocket(this, {
    host: this.host,
    port: this.port,
    protocol: this.protocol
  });
  this.mock        = options.mock;
  this.globalTags  = typeof options.globalTags === 'object' ?
      helpers.formatTags(options.globalTags, options.telegraf) : [];
  if (process.env.DD_ENTITY_ID) {
    this.globalTags = this.globalTags.filter((item) => {
      return item.indexOf('dd.internal.entity_id:') !== 0;
   });
    this.globalTags.push('dd.internal.entity_id:'.concat(helpers.sanitizeTags(process.env.DD_ENTITY_ID)));
  }
  this.telegraf    = options.telegraf || false;
  this.maxBufferSize = options.maxBufferSize || 0;
  this.sampleRate  = options.sampleRate || 1;
  this.bufferFlushInterval = options.bufferFlushInterval || 1000;
  this.bufferHolder = options.isChild ? options.bufferHolder : { buffer: '' };
  this.errorHandler = options.errorHandler;

  // If we're mocking the client, create a buffer to record the outgoing calls.
  if (this.mock) {
    this.mockBuffer = [];
  }

  // We only want a single flush event per parent and all its child clients
  if (!options.isChild && this.maxBufferSize > 0) {
    this.intervalHandle = setInterval(this.onBufferFlushInterval.bind(this), this.bufferFlushInterval);
  }

  if (options.isChild) {
    if (options.dnsError) {
      this.dnsError = options.dnsError;
    }
  } else if (options.cacheDns === true) {
    dns.lookup(options.host, (err, address) => {
      if (err === null) {
        self.host = address;
      } else {
        self.dnsError = err;
      }
    });
  }

  if (!options.isChild && options.errorHandler) {
    this.socket.on('error', options.errorHandler);
  }

  if (options.globalize) {
    global.statsd = this;
  }

  if (options.useDefaultRoute) {
    const defaultRoute = helpers.getDefaultRoute();
    if (defaultRoute) {
      console.log(`Got ${defaultRoute} for the system's default route`);
      this.host = defaultRoute;
    }
  }

  this.messagesInFlight = 0;
  this.CHECKS = {
    OK: 0,
    WARNING: 1,
    CRITICAL: 2,
    UNKNOWN: 3,
  };
}
1358698
public function init()
    {
        if ($this->isEnabled()) {
            $this->xmppclient = \PHPDaemon\Clients\XMPP\Pool::getInstance();
        }
    }
1146985
function Socket() {
  this.server = null;
  this.socks = [];
  this.settings = {};
  this.set('hwm', Infinity);
  this.set('identity', String(process.pid));
  this.retry = 0
  this.set('retry timeout', 100);
  this.set('retry max timeout', 5000);
  this.set('max retry', 100);
}
1037348
function Socket() {
  this.socks = [];
  this.settings = {};
  this.connected = false;
  this.set('identity', String(process.pid));
  this.set('retry timeout', 100);
  this.set('retry max timeout', 5000);
}
449127
def main():
    """"""
    args = setup_parser().parse_args()
    host = getattr(args, "host")
    port = getattr(args, "port")
    ipv4 = socket.gethostbyname(host)
    interval = getattr(args, "interval")

    receiver = McDevice(ipv4, udp_port=port, mc_interval=interval)
    receiver.handle_status()

    # wait for UDP messages
    while True:
        time.sleep(0.2)
122931
def _init(self):
        
        self.tn = telnetlib.Telnet(self.ip, self.port)
        self.tn.read_until('User Name')
        self.tn.write('apc\r\n')
        self.tn.read_until('Password')
        self.tn.write('apc\r\n')
        self.until_done()
1105669
public synchronized void init() {
        channelFactory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        datagramChannelFactory = new NioDatagramChannelFactory(
                Executors.newCachedThreadPool());

        timer = new HashedWheelTimer();
    }
222034
public void initialize() throws IOException, NotInitializedException {
    logger.debug("Initialising TCPTransportClient. Origin address is [{}] and destination address is [{}]", origAddress, destAddress);
    if (destAddress == null) {
      throw new NotInitializedException("Destination address is not set");
    }
    socketChannel = SelectorProvider.provider().openSocketChannel();

    try {
      if (origAddress != null) {
        socketChannel.socket().bind(origAddress);
      }

      socketChannel.connect(destAddress);
      //PCB added logging
      socketChannel.configureBlocking(BLOCKING_IO);
      getParent().onConnected();
    }
    catch (IOException e) {
      if (origAddress != null) {
        socketChannel.socket().close();
      }
      socketChannel.close();
      throw e;
    }
  }
1008578
function (msg) {
    var self = this;
    if (self.socket) {
      if (Meteor._printSentDDP)
        Meteor._debug("Sent DDP", stringifyDDP(msg));
      self.socket.send(stringifyDDP(msg));
    }
  }
1374250
private function initWebsocketServer()
    {
        $websocketBind = $this->sandstoneApplication['sandstone.websocket.server']['bind'];
        $websocketPort = $this->sandstoneApplication['sandstone.websocket.server']['port'];

        $socket = new ReactSocketServer("$websocketBind:$websocketPort", $this->loop);

        new IoServer(
            new HttpServer(
                new WsServer(
                    new ServerProtocol(
                        new WebsocketApplication(
                            $this->sandstoneApplication
                        )
                    )
                )
            ),
            $socket
        );
    }