Simulate a modbus-RTU port using C701 UDP-to-Serial bridge.

@param ip
@param options
@constructor
163670
function(ip, options) {
    var modbus = this;
    this.ip = ip;
    this.openFlag = false;

    // options
    if (typeof(options) === "undefined") options = {};
    this.port = options.port || C701_PORT; // C701 port

    // create a socket
    this._client = dgram.createSocket("udp4");

    // wait for answer
    this._client.on("message", function(data) {
        var buffer = null;

        // check expected length
        if (modbus.length < 6) return;

        // check message length
        if (data.length < (116 + 5)) return;

        // check the C701 packet magic
        if (data.readUInt16LE(2) !== 602) return;

        // check for modbus valid answer
        // get the serial data from the C701 packet
        buffer = data.slice(data.length - modbus._length);

        modbusSerialDebug({ action: "receive c701 upd port", data: data, buffer: buffer });
        modbusSerialDebug(JSON.stringify({ action: "receive c701 upd port strings", data: data, buffer: buffer }));

        // check the serial data
        if (_checkData(modbus, buffer)) {
            modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
            modbusSerialDebug(JSON.stringify({ action: "emit data serial rtu buffered port strings", buffer: buffer }));

            modbus.emit("data", buffer);
        } else {
            // check for modbus exception
            // get the serial data from the C701 packet
            buffer = data.slice(data.length - 5);

            // check the serial data
            if (_checkData(modbus, buffer)) {
                modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
                modbusSerialDebug(JSON.stringify({
                    action: "emit data serial rtu buffered port strings",
                    buffer: buffer
                }));

                modbus.emit("data", buffer);
            }
        }
    });

    this._client.on("listening", function() {
        modbus.openFlag = true;
    });

    this._client.on("close", function() {
        modbus.openFlag = false;
    });

    /**
     * Check if port is open.
     *
     * @returns {boolean}
     */
    Object.defineProperty(this, "isOpen", {
        enumerable: true,
        get: function() {
            return this.openFlag;
        }
    });

    EventEmitter.call(this);
}
101898
function init(options) {
  options = options || {}
  var port = options.port || 6466
  global.client = global.client || socketIOClient(`http://localhost:${port}`)
  client = global.client
  log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
  client.emit('join', ioid) // first join for serialization
  client.on('disconnect', client.disconnect)
  client.on('take', hasher.handle) // add listener
  
  // add methods
  client.pass = pass
  client.clientPass = clientPass
  return client
}
1020476
public static Transport UDPInstance(SocketAddress addr) throws IOException {
        DatagramSocket sock = new DatagramSocket();
        sock.setSoTimeout(getTimeout());
        sock.connect(addr);

        StreamTransport trans = new StreamTransport();
        trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
        trans.setAddressLabel(addr.toString());
        return trans;
    }
1058090
static void setSocketOption(FileDescriptor fd, ProtocolFamily family,
                                SocketOption<?> name, Object value)
        throws IOException
    {
        if (value == null)
            throw new IllegalArgumentException("Invalid option value");

        // only simple values supported by this method
        Class<?> type = name.type();
        if (type != Integer.class && type != Boolean.class)
            throw new AssertionError("Should not reach here");

        // special handling
        if (name == StandardSocketOptions.SO_RCVBUF ||
            name == StandardSocketOptions.SO_SNDBUF)
        {
            int i = ((Integer)value).intValue();
            if (i < 0)
                throw new IllegalArgumentException("Invalid send/receive buffer size");
        }
        if (name == StandardSocketOptions.SO_LINGER) {
            int i = ((Integer)value).intValue();
            if (i < 0)
                value = Integer.valueOf(-1);
            if (i > 65535)
                value = Integer.valueOf(65535);
        }
        if (name == StandardSocketOptions.IP_TOS) {
            int i = ((Integer)value).intValue();
            if (i < 0 || i > 255)
                throw new IllegalArgumentException("Invalid IP_TOS value");
        }
        if (name == StandardSocketOptions.IP_MULTICAST_TTL) {
            int i = ((Integer)value).intValue();
            if (i < 0 || i > 255)
                throw new IllegalArgumentException("Invalid TTL/hop value");
        }

        // map option name to platform level/name
        OptionKey key = SocketOptionRegistry.findOption(name, family);
        if (key == null)
            throw new AssertionError("Option not found");

        int arg;
        if (type == Integer.class) {
            arg = ((Integer)value).intValue();
        } else {
            boolean b = ((Boolean)value).booleanValue();
            arg = (b) ? 1 : 0;
        }

        boolean mayNeedConversion = (family == UNSPEC);
        setIntOption0(fd, mayNeedConversion, key.level(), key.name(), arg);
    }
926352
function(port, host, opts) {
  if (!(this instanceof Connector)) {
    return new Connector(port, host, opts);
  }

  EventEmitter.call(this);

  this.opts = opts || {};
  this.port = port;
  this.host = host;
  this.useDict = opts.useDict;
  this.useProtobuf = opts.useProtobuf;
  this.handshake = new Handshake(opts);
  this.heartbeat = new Heartbeat(opts);
  this.distinctHost = opts.distinctHost;
  this.ssl = opts.ssl;

  this.switcher = null;
}
771620
public static NetworkPort remotePort(String hostname, int port){
        return new RemoteNetworkPort(hostname, port, NetworkPort.Type.TCP);
    }
1094293
function init(options) {
    if (options === void 0) { options = {}; }
    if ('debug' in options) {
        diag.debug.enabled = options.debug;
        Q.longStackSupport = options.debug;
    }
    if ('serverUrl' in options) {
        var myURL = url.parse(options.serverUrl);
        if (!myURL.protocol && !myURL.host) {
            return Q.reject(new Error(options.serverUrl + " is not an accepted Url, please add a Host and a Protocol."));
        }
    }
    _.assignWith(exports.initOptions, cloneServerInitOptions(options), function (left, right) { return _.isUndefined(right) ? left : right; });
    if ('push' in options) {
        exports.initOptions.push = _.cloneDeep(options.push);
    }
    return device.ready;
}
538420
public void setIP(byte[] ip) {
        buffer[INDEX_IP] = ip[0];
        buffer[INDEX_IP + 1] = ip[1];
        buffer[INDEX_IP + 2] = ip[2];
        buffer[INDEX_IP + 3] = ip[3];
    }
130373
private void prepareTransport(boolean useRtuOverTcp) throws IOException {

        // If we don't have a transport, or the transport type has changed
        if (transport == null || (this.useRtuOverTcp != useRtuOverTcp)) {

            // Save the flag to tell us which transport type to use
            this.useRtuOverTcp = useRtuOverTcp;

            // Select the correct transport
            if (useRtuOverTcp) {
                logger.trace("prepareTransport() -> using RTU over TCP transport.");
                transport = new ModbusRTUTCPTransport(socket);
                transport.setMaster(this);
            }
            else {
                logger.trace("prepareTransport() -> using standard TCP transport.");
                transport = new ModbusTCPTransport(socket);
                transport.setMaster(this);
            }
        }
        else {
            logger.trace("prepareTransport() -> using custom transport: {}", transport.getClass().getSimpleName());
            transport.setSocket(socket);
        }
        transport.setTimeout(timeout);
    }
657372
def _try_options(options, exceptions,
                 jid, metadata, negotiation_timeout, loop, logger):
    
    for host, port, conn in options:
        logger.debug(
            "domain %s: trying to connect to %r:%s using %r",
            jid.domain, host, port, conn
        )
        try:
            transport, xmlstream, features = yield from conn.connect(
                loop,
                metadata,
                jid.domain,
                host,
                port,
                negotiation_timeout,
                base_logger=logger,
            )
        except OSError as exc:
            logger.warning(
                "connection failed: %s", exc
            )
            exceptions.append(exc)
            continue

        logger.debug(
            "domain %s: connection succeeded using %r",
            jid.domain,
            conn,
        )

        if not metadata.sasl_providers:
            return transport, xmlstream, features

        try:
            features = yield from security_layer.negotiate_sasl(
                transport,
                xmlstream,
                metadata.sasl_providers,
                negotiation_timeout=None,
                jid=jid,
                features=features,
            )
        except errors.SASLUnavailable as exc:
            protocol.send_stream_error_and_close(
                xmlstream,
                condition=errors.StreamErrorCondition.POLICY_VIOLATION,
                text=str(exc),
            )
            exceptions.append(exc)
            continue
        except Exception as exc:
            protocol.send_stream_error_and_close(
                xmlstream,
                condition=errors.StreamErrorCondition.UNDEFINED_CONDITION,
                text=str(exc),
            )
            raise

        return transport, xmlstream, features

    return None
1268606
public static function udp(string $host, array $options = []) : Socket
    {
        return self::create($host, \array_merge($options, [
            'transport' => 'udp',
            'buffer_size' => 65507,
        ]));
    }
1053942
static <T> boolean setOption(Channel jdkChannel, NioChannelOption<T> option, T value) {
        java.nio.channels.NetworkChannel channel = (java.nio.channels.NetworkChannel) jdkChannel;
        if (!channel.supportedOptions().contains(option.option)) {
            return false;
        }
        if (channel instanceof ServerSocketChannel && option.option == java.net.StandardSocketOptions.IP_TOS) {
            // Skip IP_TOS as a workaround for a JDK bug:
            // See http://mail.openjdk.java.net/pipermail/nio-dev/2018-August/005365.html
            return false;
        }
        try {
            channel.setOption(option.option, value);
            return true;
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
199742
function printList(serialList) {
  menu = createSelect();
  var title = createElement('option', 'Choose a port:');
  menu.child(title);
  menu.position(10, 10);
  menu.changed(openPort);
  for (var i = 0; i < serialList.length; i++) {
    var thisOption = createElement('option', serialList[i]);
    thisOption.value = serialList[i];
    menu.child(thisOption);
    println(i + " " + serialList[i]);
  }
}
1299633
public static boolean canTelnet(String ip, int port, int timeout) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), timeout);
            return socket.isConnected() && !socket.isClosed();
        } catch (Exception e) {
            return false;
        } finally {
            IOUtils.closeQuietly(socket);
        }
    }
802930
@Override
	public void addSipConnector(String ipAddress, int port, String transport) throws LifecycleException
	{
		SipConnector sipConnector = mssContainer.createSipConnector(ipAddress, port, transport);
		mssContainer.addSipConnector(sipConnector);
	}
66856
function SSH(options) {
	this.options = options || {};
	console.assert(this.options.hostname, "Hostname required!");

	this.debug = !!options.debug;
	this.listener = new Listener({
		debug: options.debug
	});
}
80685
def _launch_remote(self, host, config_port, race, name, interface):
    """"""
    self._tcp_conn, settings = tcp_client(Addr(host, config_port))

    self._map_name = settings["map_name"]

    if settings["remote"]:
      self._udp_sock = udp_server(
          Addr(host, settings["ports"]["server"]["game"]))

      daemon_thread(tcp_to_udp,
                    (self._tcp_conn, self._udp_sock,
                     Addr(host, settings["ports"]["client"]["game"])))

      daemon_thread(udp_to_tcp, (self._udp_sock, self._tcp_conn))

    extra_ports = [
        settings["ports"]["server"]["game"],
        settings["ports"]["server"]["base"],
        settings["ports"]["client"]["game"],
        settings["ports"]["client"]["base"],
    ]

    self._sc2_procs = [self._run_config.start(
        extra_ports=extra_ports, host=host, version=settings["game_version"],
        window_loc=(700, 50), want_rgb=interface.HasField("render"))]
    self._controllers = [p.controller for p in self._sc2_procs]

    # Create the join request.
    join = sc_pb.RequestJoinGame(options=interface)
    join.race = race
    join.player_name = name
    join.shared_port = 0  # unused
    join.server_ports.game_port = settings["ports"]["server"]["game"]
    join.server_ports.base_port = settings["ports"]["server"]["base"]
    join.client_ports.add(game_port=settings["ports"]["client"]["game"],
                          base_port=settings["ports"]["client"]["base"])

    self._controllers[0].save_map(settings["map_path"], settings["map_data"])
    self._controllers[0].join_game(join)