Get dynamically assigned server port? - apache-httpcomponents

When I call
import org.apache.http.impl.nio.bootstrap.*;
import java.net.InetSocketAddress;
HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(0)
// ...
.create();
server.start();
How do I get the actual port number assigned to the server?
I tried
int port = ((InetSocketAddress) server.getEndpoint().getAddress()).getPort();
But that just returned 0

HttpComponents hide a lot of the internals and especially what you are looking for, a workaround would be to retrieve a port outside the library and use it:
int port;
try (ServerSocket socket = new ServerSocket()) {
socket.setReuseAddress(false);
socket.bind(new InetSocketAddress(0));
port = socket.getLocalPort();
}
HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(port)
// ...
.create();
server.start();

Related

How do I connect to an Infura web socket in Ethers.js?

I know in Web3js you can connect to an Infura web socket like so:
const Web3 = require('web3')
const web3 = new Web3(
new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws/v3/<project_id>")
)
but how do I connect using Ethers.js? I've tried searching the internet but the answer isn't immediately obvious.
Found it in the Ether.js docs:
const provider = new ethers.providers.WebSocketProvider(
"wss://mainnet.infura.io/ws/v3/<project_id>"
)
the mainnet is used by default, but you can specify also specify a test network:
// Using a test network
const provider = new ethers.providers.WebSocketProvider(
"wss://rinkeby.infura.io/ws/v3/<project_id>", "rinkeby"
)

Unable to create a client-server connection in ignite

I have successfully created a connection between client and server(localhost) in ignite.But while trying to connect the ignite server which is running in remote IP(eg: 192.168.33.44), I am not able to establish connection. The client side configuration given below.
#Bean(name = "igniteConfiguration")
public IgniteConfiguration igniteConfiguration() {
IgniteConfiguration igniteConfiguration = new IgniteConfiguration();
igniteConfiguration.setClientMode(true);
igniteConfiguration.setPeerClassLoadingEnabled(true);
igniteConfiguration.setLocalHost("127.0.0.1");
TcpDiscoverySpi tcpDiscoverySpi = new TcpDiscoverySpi();
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Collections.singletonList("127.0.0.1:47500..47509"));
tcpDiscoverySpi.setIpFinder(ipFinder);
tcpDiscoverySpi.setLocalPort(47500);
// Changing local port range. This is an optional action.
tcpDiscoverySpi.setLocalPortRange(9);
tcpDiscoverySpi.setLocalAddress("localhost");
igniteConfiguration.setDiscoverySpi(tcpDiscoverySpi);
TcpCommunicationSpi communicationSpi = new TcpCommunicationSpi();
communicationSpi.setLocalAddress("localhost");
communicationSpi.setLocalPort(48100);
communicationSpi.setSlowClientQueueLimit(1000);
igniteConfiguration.setCommunicationSpi(communicationSpi);
igniteConfiguration.setCacheConfiguration(cacheConfiguration());
return igniteConfiguration;
}
Can anyone help me to make code change for creating a successful client-server connecion.Thanks in advance.
Since you are moving from localhost deployment, you need to do the following changes:
TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder();
ipFinder.setAddresses(Collections.singletonList("192.168.33.44:47500..47509"));
Most likely, the server configurations need to be changed as well.

IBM IOT C# client thowing invalid ip address exception when constructing gatewayclient

I am beginning to use the sample IBM-IOT C# sample code as per
https://github.com/ibm-watson-iot/iot-csharp/blob/master/docs/Gateway.rst
however I get "An invalid IP address was specified." thrown when the gateway constructor is called using the org id.
I'm using an orgid of 'p3wg4w' (set in config and accessed as a string property Globals.WatsonOrgID" )
my code is
private static void InitGatewayClient()
{
if (gw == null)
{
gw = new GatewayClient(Globals.WatsonOrgID,
Globals.WatsonGatewayDeviceType,
Globals.WatsonGatewayDeviceID,
Globals.WatsonAuthMethod,
Globals.WatsonToken);
gw.commandCallback += processCommand;
gw.errorCallback += processError;
gw.connect();
Console.WriteLine("Gateway connected");
Console.WriteLine("publishing gateway events..");
}
}
Has anyone seen this before ?
check if you can access or if you can:
telnet p3wg4w.messaging.internetofthings.ibmcloud.com 8883
The libraries aren't using any IP to create the connection, it is using the below vars
public static string DOMAIN = ".messaging.internetofthings.ibmcloud.com";
public static int MQTTS_PORT = 8883;
I can only think that your firewall is blocking the connection
I've used the below sample and worked just fine for me:
https://github.com/ibm-watson-iot/iot-csharp/blob/master/sample/Gateway/SampleGateway.cs

Error trying to connect using Astyanax to Cassandra hosted on a EC2 instance

I am getting the following error "astyanax.connectionpool.exceptions.PoolTimeoutException:" when trying to use client Astyanax to connect to Cassandra on a EC2 instance. Need help
Following is my code snippet.
import org.mortbay.jetty.servlet.Context;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.CqlResult;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
public class MetadataRS {
public static void main(String args[]){
AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
.forCluster("ClusterName")
.forKeyspace("KeyspaceName")
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
.setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN)
)
.withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
.setPort(9042)
.setMaxConnsPerHost(40)
.setSeeds("<EC2-IP>:9042")
.setConnectTimeout(5000)
)
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
Keyspace keyspace = context.getEntity();
System.out.println(keyspace);
ColumnFamily<String, String> CF_USER_INFO =
new ColumnFamily<String, String>(
"Standard1", // Column Family Name
StringSerializer.get(), // Key Serializer
StringSerializer.get()); // Column
OperationResult<ColumnList<String>> result = null;
try {
result = keyspace.prepareQuery(CF_USER_INFO)
.getKey("user_id_hash")
.execute();
} catch (ConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ColumnList<String> columns = result.getResult();
// Lookup columns in response by name
String uid = columns.getColumnByName("user_id_hash").getStringValue();
System.out.println(uid);
// Or, iterate through the columns
for (Column<String> c : result.getResult()) {
System.out.println(c.getName());
}
}
}
Error
com.netflix.astyanax.thrift.ThriftKeyspaceImpl#1961f4
com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException: PoolTimeoutException: [host=():9042, latency=5001(5001), attempts=1] Timed out waiting for connection
at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.waitForConnection(SimpleHostConnectionPool.java:201)
at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.borrowConnection(SimpleHostConnectionPool.java:158)
at com.netflix.astyanax.connectionpool.impl.RoundRobinExecuteWithFailover.borrowConnection(RoundRobinExecuteWithFailover.java:60)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:50)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:229)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$1.execute(ThriftColumnFamilyQueryImpl.java:180)
at com.rjil.jiodrive.rs.MetadataRS.main(MetadataRS.java:57)
Exception in thread "main" java.lang.NullPointerException
at com.rjil.jiodrive.rs.MetadataRS.main(MetadataRS.java:62)
Since you are running cassandra on EC2 instance, check that the cassandra's port no. (which you have choosen as 9042) is in the allowed list of ec2 security group and that you have access to it. If not add the port no. in the inbound list of the ec2 security group and set the ip ranges as 0.0.0.0.
Alos check the firewall on the ec2 is turned off. By default its false, but its good to check it anyway.
If you have done this, then your client might be behind a firewall that prevents outbound traffic to your choosen port (9042).
Lastly if you have not used any elastic ip, its better to use the ec2 instance dns name, both in your setSeeds section and in the rpc_address of cassandra.yaml
Your issue is not in your code. You have a connectivity problem to the node you specified as your seed. So either that node isn't running, or you can't reach it from the machine running your client.
I finally upgraded libthrift to 0.9 and changed my code to the following nd it working fine now.
public Keyspace getDBConnection() {
if (poolConfig == null) {
poolConfig = new ConnectionPoolConfigurationImpl(
"CassandraPool").setPort(port).setMaxConnsPerHost(1)
.setSeeds((new StringBuilder(seedHost).append(":").append(port).toString()))
.setLatencyAwareUpdateInterval(latencyAwareUpdateInterval) // Will resort hosts per
// token partition every
// 10 seconds
.setLatencyAwareResetInterval(latencyAwareResetInterval) // Will clear the latency
// every 10 seconds. In
// practice I set this
// to 0 which is the
// default. It's better
// to be 0.
.setLatencyAwareBadnessThreshold(latencyAwareBadnessThreshold) // Will sort hosts if a host
// is more than 100% slower
// than the best and always
// assign connections to the
// fastest host, otherwise
// will use round robin
.setLatencyAwareWindowSize(latencyAwareWindowSize) // Uses last 100 latency
// samples. These samples are in
// a FIFO q and will just cycle
// themselves.
.setTimeoutWindow(60000)
;
}
AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
.forCluster(clusterName)
.forKeyspace(keyspaceName)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl().setDiscoveryType(
NodeDiscoveryType.NONE)
.setConnectionPoolType(
ConnectionPoolType.ROUND_ROBIN)
.setCqlVersion("3.0.0")
.setTargetCassandraVersion("2.0"))
.withConnectionPoolConfiguration(poolConfig)
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
return context.getClient();
}

What is the purpose of a resource in a WebSocket URL?

Looking at the W3 spec on WebSockets, I see
var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0)
socket.send(getUpdateData());
}, 50);
};
I understand that the socket services lives on port 12010 at game.example.com, but what is the purpose of the '/updates' resource in the URL? If the service lives at some port, what good will a resource do?
You can expose different logical WebSockets on the same port, using different URI's.
Lets take chat as an example. You could use the URI to determine the particular channel or chat room you want to join.
var socket = new WebSocket('ws://chat.example.com/games');
var socket = new WebSocket('ws://chat.example.com/movies');
var socket = new WebSocket('ws://chat.example.com/websockets');
You can also use query strings. Imagine a stock ticker:
var socket = new WebSocket('ws://www.example.com/ticker?code=MSFT');
var socket = new WebSocket('ws://www.example.com/ticker?code=GOOG');

Resources