Open TCP socket and set it as escpos device
324506
def open(self):
        
        self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.device.connect((self.host, self.port))

        if self.device is None:
            print "Could not open socket for %s" % self.host
720549
def _netmiko_open(self, device_type, netmiko_optional_args=None):
        """"""
        if netmiko_optional_args is None:
            netmiko_optional_args = {}
        try:
            self._netmiko_device = ConnectHandler(
                device_type=device_type,
                host=self.hostname,
                username=self.username,
                password=self.password,
                timeout=self.timeout,
                **netmiko_optional_args
            )
        except NetMikoTimeoutException:
            raise ConnectionException("Cannot connect to {}".format(self.hostname))

        # ensure in enable mode
        self._netmiko_device.enable()
        return self._netmiko_device
1140912
def bind(self, family, type, proto=0):
        """"""
        self.socket = socket.socket(family, type, proto)
        prevent_socket_inheritance(self.socket)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if self.nodelay and not isinstance(self.bind_addr, str):
            self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        
        if self.ssl_adapter is not None:
            self.socket = self.ssl_adapter.bind(self.socket)
        
        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See http://www.cherrypy.org/ticket/871.
        if (family == socket.AF_INET6
            and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
            try:
                self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass
        
        self.socket.bind(self.bind_addr)
1076783
function TcpConnect (socket) {
    this.count ++;    // increment client count inside this server
    socket.uid = "Socket://" + socket.remoteAddress +":" + socket.remotePort;
    socket.controller = this.controller;
    socket.adapter   = this.adapter;
    socket.controller.Debug(4, "N°:%d Server=[%s] Client: [%s]"
             ,this.count,this.uid,socket.uid);            
        
    // attach new device object to client socket
    socket.device = new TcpClient (socket);
    
    // notify adapter that it has a new client device connected
    if (socket.adapter.ClientConnect (socket) === -1) {
        try {socket.end();} catch(e){};
        return;
    }
  
    // send any received data to device parser
    socket.on(this.evtname, function(buffer) {
	    socket.controller.Debug(7, "%s Data=[%s]", socket.device.uid, buffer);
        // call adapter specific method to process messages
        socket.adapter.ParseBuffer(socket, buffer);
    });
    
    // On error close socket
    socket.on('error', function (err) {
        socket.controller.Debug(3, "%s ERROR=[%s]", socket.device.uid, err);
        this.adapter.ClientQuit(socket);
        try {socket.destroy();} catch(e){};
    });
        
    // Remove the device from gateway active device list and notify adapter for eventual cleanup
    socket.on('end', function () {
	socket.controller.Debug(4, "SockClient Quit devid=%s uid=%s", socket.device.devid, socket.device.uid);
        this.adapter.ClientQuit(socket);
    });
    
}
334492
function SocketPeer (opts) {
  var self = this;

  if (!(self instanceof SocketPeer)) {
    return new SocketPeer(opts);
  }

  opts = opts || {};

  EventEmitter.call(self);

  self._connections = {
    socket: {success: 0, error: 0, attempt: 0},
    rtc: {success: 0, error: 0, attempt: 0}
  };
  self.peer = null;
  self.rtcConnected = false;
  self.socketConnected = false;

  extend(self, {
    pairCode: 'pairCode' in opts ? opts.pairCode : null,
    socketFallback: 'socketFallback' in opts ? opts.socketFallback : true,
    socket: 'socket' in opts ? opts.socket : null,
    stream: 'stream' in opts ? opts.stream : null,
    url: 'url' in opts ? opts.url : 'http://localhost',
    reconnect: 'reconnect' in opts ? opts.reconnect : true,
    reconnectDelay: 'reconnectDelay' in opts ? opts.reconnectDelay : 1000,
    timeout: 'timeout' in opts ? opts.timeout : 0,
    autoconnect: 'autoconnect' in opts ? opts.autoconnect : true,
    debug: 'debug' in opts ? opts.debug : false
  }, opts);

  self._debug('New peer');

  self.on('peer.found', function (data) {
    self.socketConnected = true;
    clearTimeout(self._socketConnectTimeout);
    clearTimeout(self._socketReconnectDelayTimeout);
    self._connections.socket.attempt = 0;
    self._connections.socket.success++;

    self.emit('connect');
    if (self._connections.socket.success > 0) {
      self.emit('reconnect');
    }

    self.initiator = data.initiator;

    if (data.initiator) {
      self._send('rtc.connect');
      self._rtcInit();
    }
  });
  self.on('rtc.signal', self._rtcSignal);
  self.on('rtc.connect', function () {
    self._rtcInit();
  });

  self.on('busy', function () {
    self._socketError(new Error('Pair code "' + self.pairCode + '" already in use'));
    self.socket.close();
  });

  if (self.autoconnect) {
    setTimeout(function () {
      self.connect();
    }, 0);
  }
}
1279125
def start(self):
        """"""
        # We don't have to trap KeyboardInterrupt or SystemExit here,
        # because cherrpy.server already does so, calling self.stop() for us.
        # If you're using this server with another framework, you should
        # trap those exceptions in whatever code block calls start().
        self._interrupt = None
        
        if self.software is None:
            self.software = "%s Server" % self.version
        
        # SSL backward compatibility
        if (self.ssl_adapter is None and
            getattr(self, 'ssl_certificate', None) and
            getattr(self, 'ssl_private_key', None)):
            warnings.warn(
                    "SSL attributes are deprecated in CherryPy 3.2, and will "
                    "be removed in CherryPy 3.3. Use an ssl_adapter attribute "
                    "instead.",
                    DeprecationWarning
                )
            try:
                from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter
            except ImportError:
                pass
            else:
                self.ssl_adapter = pyOpenSSLAdapter(
                    self.ssl_certificate, self.ssl_private_key,
                    getattr(self, 'ssl_certificate_chain', None))
        
        # Select the appropriate socket
        if isinstance(self.bind_addr, basestring):
            # AF_UNIX socket
            
            # So we can reuse the socket...
            try: os.unlink(self.bind_addr)
            except: pass
            
            # So everyone can access the socket...
            try: os.chmod(self.bind_addr, 0777)
            except: pass
            
            info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
        else:
            # AF_INET or AF_INET6 socket
            # Get the correct address family for our host (allows IPv6 addresses)
            host, port = self.bind_addr
            try:
                info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                          socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
            except socket.gaierror:
                if ':' in self.bind_addr[0]:
                    info = [(socket.AF_INET6, socket.SOCK_STREAM,
                             0, "", self.bind_addr + (0, 0))]
                else:
                    info = [(socket.AF_INET, socket.SOCK_STREAM,
                             0, "", self.bind_addr)]
        
        self.socket = None
        msg = "No socket could be created"
        for res in info:
            af, socktype, proto, canonname, sa = res
            try:
                self.bind(af, socktype, proto)
            except socket.error:
                if self.socket:
                    self.socket.close()
                self.socket = None
                continue
            break
        if not self.socket:
            raise socket.error(msg)
        
        # Timeout so KeyboardInterrupt can be caught on Win32
        self.socket.settimeout(1)
        self.socket.listen(self.request_queue_size)
        
        # Create worker threads
        self.requests.start()
        
        self.ready = True
        while self.ready:
            self.tick()
            if self.interrupt:
                while self.interrupt is True:
                    # Wait for self.stop() to complete. See _set_interrupt.
                    time.sleep(0.1)
                if self.interrupt:
                    raise self.interrupt
727893
def open_ports(start, end, protocol="TCP"):
    """"""
    _args = ['open-port']
    _args.append('{}-{}/{}'.format(start, end, protocol))
    subprocess.check_call(_args)
459076
function ClientConnection(options) {

    if (options.udp4 === true && options.tcp === true) {
        throw new Error('Both udp and tcp are set as protocol.  Devices can only communicate in one protocol.');
    }
    if (options.udp4 === false && options.tcp === false) {
        throw new Error('Neither UDP or TCP is set.  Devices must communicate in one protocol.');
    }

    if (options.udp4) {
        this.enable_compression = true;
        this.createProxySocket('udp4', options.proxyUrl, options.port);
    } else {
        this.enable_compression = false;
        this.createProxySocket('tcp', options.proxyUrl, options.port);
    }

    this.log = options.log;

    EventEmitter.call(this);
}
158736
def create_client_socket(self, config):
		
		client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config)
		client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
		return client_socket
689607
function Socket (opts) {
  if ('string' == typeof opts) {
    var uri = util.parseUri(opts);
    opts = arguments[1] || {};
    opts.host = uri.host;
    opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
    opts.port = uri.port;
  }

  opts = opts || {};
  this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' == location.protocol);
  this.host = opts.host || opts.hostname || (global.location ? location.hostname : 'localhost');
  this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80));
  this.query = opts.query || {};
  this.query.uid = rnd();
  this.upgrade = false !== opts.upgrade;
  this.resource = opts.resource || 'default';
  this.path = (opts.path || '/engine.io').replace(/\/$/, '');
  this.path += '/' + this.resource + '/';
  this.forceJSONP = !!opts.forceJSONP;
  this.timestampParam = opts.timestampParam || 't';
  this.timestampRequests = !!opts.timestampRequests;
  this.flashPath = opts.flashPath || '';
  this.transports = opts.transports || ['polling', 'websocket', 'flashsocket'];
  this.readyState = '';
  this.writeBuffer = [];
  this.policyPort = opts.policyPort || 843;
  this.open();

  Socket.sockets.push(this);
  Socket.sockets.evs.emit('add', this);
}
569077
async def start_client(self,
                           sock: anyio.abc.SocketStream,
                           addr,
                           path: str,
                           headers: Optional[List] = None,
                           subprotocols: Optional[List[str]] = None):
        
        self._sock = sock
        self._connection = WSConnection(ConnectionType.CLIENT)
        if headers is None:
            headers = []
        if subprotocols is None:
            subprotocols = []
        data = self._connection.send(
            Request(
                host=addr[0],
                target=path,
                extra_headers=headers,
                subprotocols=subprotocols))
        await self._sock.send_all(data)

        assert self._scope is None
        self._scope = True
        try:
            event = await self._next_event()
            if not isinstance(event, AcceptConnection):
                raise ConnectionError("Failed to establish a connection",
                                      event)
            return event
        finally:
            self._scope = None
1218815
def main(pub_port=None, sub_port=None):
    '''
    '''
    try:
        if sub_port is None:
            sub_port = get_sub_port()
        if pub_port is None:
            pub_port = get_pub_port()
        context = zmq.Context(1)
        frontend = context.socket(zmq.SUB)
        backend = context.socket(zmq.PUB)

        frontend.bind('tcp://*:{pub_port}'.format(pub_port=pub_port))
        frontend.setsockopt(zmq.SUBSCRIBE, b'')
        backend.bind('tcp://*:{sub_port}'.format(sub_port=sub_port))
        zmq.device(zmq.FORWARDER, frontend, backend)
    except KeyboardInterrupt:
        pass
    finally:
        frontend.close()
        backend.close()
        context.term()
1010584
def connect
      @socket = TCPSocket.open(@options[:host], @options[:port])
      @server_protocol_version = BinData::Int16be.read(socket)

      # minimal protocol version we are supporting is 19
      raise ProtocolVersionError, "Protocols 19 and above are supported. Please upgrade your OrientDb server." if @server_protocol_version < 19

      server_protocol_string = "OrientdbBinary::Protocol::Protocol#{@server_protocol_version}"
      constant = Object.const_defined?(server_protocol_string) ? Object.const_get(server_protocol_string) : OrientdbBinary::Protocol::Protocol19
      @protocol = constant
    end
905348
def bind(self, family, type, proto=0):
        """"""
        sock = self.prepare_socket(
            self.bind_addr,
            family, type, proto,
            self.nodelay, self.ssl_adapter,
        )
        sock = self.socket = self.bind_socket(sock, self.bind_addr)
        self.bind_addr = self.resolve_real_bind_addr(sock)
        return sock
852826
def open_socket(host, port) # :nodoc:
      return Timeout.timeout(@open_timeout, Net::OpenTimeout) {
        if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
          @passive = true
          sock = SOCKSSocket.open(host, port)
        else
          sock = TCPSocket.open(host, port)
        end
        io = BufferedSocket.new(sock)
        io.read_timeout = @read_timeout
        io
      }
    end
107934
def rpc(commands, method='cli', **kwargs):
    '''
    
    '''
    conn_args = nxos_device['conn_args']
    conn_args.update(kwargs)
    return __utils__['nxos_api.rpc'](commands, method=method, **conn_args)
1094776
def open(self):
        
        # restart TCP if already open
        if self.is_open():
            self.close()
        # init socket and connect
        # list available sockets on the target host/port
        # AF_xxx : AF_INET -> IPv4, AF_INET6 -> IPv6,
        #          AF_UNSPEC -> IPv6 (priority on some system) or 4
        # list available socket on target host
        for res in socket.getaddrinfo(self.__hostname, self.__port,
                                      socket.AF_UNSPEC, socket.SOCK_STREAM):
            af, sock_type, proto, canon_name, sa = res
            try:
                self.__sock = socket.socket(af, sock_type, proto)
            except socket.error:
                self.__sock = None
                continue
            try:
                self.__sock.settimeout(self.__timeout)
                self.__sock.connect(sa)
            except socket.error:
                self.__sock.close()
                self.__sock = None
                continue
            break
        # check connect status
        if self.__sock is not None:
            return True
        else:
            self.__last_error = const.MB_CONNECT_ERR
            self.__debug_msg('connect error')
            return False