下面列出了怎么用java.net.InetSocketAddress的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) {
// 启动服务提供者
new Thread(new Runnable() {
@Override
public void run() {
try {
RpcExporter.exporter("localhost",8088);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
// 创建服务本地代理
RpcImporter<EchoService> importer = new RpcImporter<>();
// 从服务本地代理获取服务对象类
EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8088));
System.out.println(echo.echo("Are you OK?"));
}
@Test
public void testGetOmHAAddressesById() {
OzoneConfiguration conf = new OzoneConfiguration();
conf.set(OZONE_OM_SERVICE_IDS_KEY, "ozone1");
conf.set("ozone.om.nodes.ozone1", "node1,node2,node3");
conf.set("ozone.om.address.ozone1.node1", "1.1.1.1");
conf.set("ozone.om.address.ozone1.node2", "1.1.1.2");
conf.set("ozone.om.address.ozone1.node3", "1.1.1.3");
Map<String, List<InetSocketAddress>> addresses =
OmUtils.getOmHAAddressesById(conf);
assertFalse(addresses.isEmpty());
List<InetSocketAddress> rpcAddrs = addresses.get("ozone1");
assertFalse(rpcAddrs.isEmpty());
assertTrue(rpcAddrs.stream().anyMatch(
a -> a.getAddress().getHostAddress().equals("1.1.1.1")));
assertTrue(rpcAddrs.stream().anyMatch(
a -> a.getAddress().getHostAddress().equals("1.1.1.2")));
assertTrue(rpcAddrs.stream().anyMatch(
a -> a.getAddress().getHostAddress().equals("1.1.1.3")));
}
@Test
public void testClient() throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress("localhost", PORT))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
var server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(7777));
System.out.println("server bound to " + server.getLocalAddress());
var remote = SocketChannel.open();
remote.connect(new InetSocketAddress(InetAddress.getByName(Host.NAME), 7));
//remote.configureBlocking(false);
System.out.println("accepting ...");
var client = server.accept();
//client.configureBlocking(false);
var executor = Executors.newSingleThreadExecutor();
//var executor = ForkJoinPool.commonPool();
Thread.builder().virtual(executor).task(runnable(client, remote)).start();
Thread.builder().virtual(executor).task(runnable(remote, client)).start();
}
public HttpConnectHarCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx, Har har, String currentPageRef) {
super(originalRequest, ctx);
if (har == null) {
throw new IllegalStateException("Attempted har capture when har is null");
}
if (!ProxyUtils.isCONNECT(originalRequest)) {
throw new IllegalStateException("Attempted HTTP CONNECT har capture on non-HTTP CONNECT request");
}
this.har = har;
this.currentPageRef = currentPageRef;
this.clientAddress = (InetSocketAddress) ctx.channel().remoteAddress();
// create and cache an HTTP CONNECT timing object to capture timing-related information
this.httpConnectTiming = new HttpConnectTiming();
httpConnectTimes.put(clientAddress, httpConnectTiming);
}
InetSocketAddress getDestAddress(SocketChannel localChannel) {
short portKey = (short) localChannel.socket().getPort();
NatSession session = NatSessionManager.getSession(portKey);
if (session != null) {
if (ProxyConfig.Instance.needProxy(session.RemoteIP)) {
if (ProxyConfig.IS_DEBUG)
Log.d(Constant.TAG, String.format("%d/%d:[PROXY] %s=>%s:%d", NatSessionManager.getSessionCount(),
Tunnel.SessionCount, session.RemoteHost,
CommonMethods.ipIntToString(session.RemoteIP), session.RemotePort & 0xFFFF));
return InetSocketAddress.createUnresolved(session.RemoteHost, session.RemotePort & 0xFFFF);
} else {
return new InetSocketAddress(localChannel.socket().getInetAddress(), session.RemotePort & 0xFFFF);
}
}
return null;
}
@Test
public void override_hostPort() throws Exception {
final String overrideHost = "10.99.99.99";
final int overridePort = 1234;
final String overrideHostWithPort = overrideHost + ":" + overridePort;
ProxyDetectorImpl proxyDetector = new ProxyDetectorImpl(
proxySelectorSupplier,
authenticator,
overrideHostWithPort);
ProxyParameters detected = proxyDetector.proxyFor(destination);
assertNotNull(detected);
assertEquals(
new ProxyParameters(
new InetSocketAddress(InetAddress.getByName(overrideHost), overridePort),
NO_USER,
NO_PW),
detected);
}
/**
* Tests if a network location is reachable. This is best effort and may give false
* not reachable.
*
* @param endpoint the endpoint to connect to
* @param timeout Open connection will wait for this timeout.
* @param retryCount In case of connection timeout try retryCount times.
* @param retryInterval the interval to retryCount
* @return true if the network location is reachable
*/
public static boolean isLocationReachable(
InetSocketAddress endpoint,
Duration timeout,
int retryCount,
Duration retryInterval) {
int retryLeft = retryCount;
while (retryLeft > 0) {
try (Socket s = new Socket()) {
s.connect(endpoint, (int) timeout.toMillis());
return true;
} catch (IOException e) {
} finally {
SysUtils.sleep(retryInterval);
retryLeft--;
}
}
LOG.log(Level.FINE, "Failed to connect to: {0}", endpoint.toString());
return false;
}
public CompletableFuture<JobSubmissionResult> submitJob(JobGraph jobGraph) {
final CompletableFuture<DispatcherGateway> dispatcherGatewayFuture = getDispatcherGatewayFuture();
// we have to allow queued scheduling in Flip-6 mode because we need to request slots
// from the ResourceManager
jobGraph.setAllowQueuedScheduling(true);
final CompletableFuture<InetSocketAddress> blobServerAddressFuture = createBlobServerAddress(dispatcherGatewayFuture);
final CompletableFuture<Void> jarUploadFuture = uploadAndSetJobFiles(blobServerAddressFuture, jobGraph);
final CompletableFuture<Acknowledge> acknowledgeCompletableFuture = jarUploadFuture
.thenCombine(
dispatcherGatewayFuture,
(Void ack, DispatcherGateway dispatcherGateway) -> dispatcherGateway.submitJob(jobGraph, rpcTimeout))
.thenCompose(Function.identity());
return acknowledgeCompletableFuture.thenApply(
(Acknowledge ignored) -> new JobSubmissionResult(jobGraph.getJobID()));
}
@Override
public Statement apply(final Statement statement, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
server = HttpServer.create(new InetSocketAddress(0), 0);
configurers.forEach(it -> it.accept(server, (exchange, status, payload) -> {
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, payload.length);
try (final OutputStream os = exchange.getResponseBody()) {
os.write(payload);
}
}));
server.start();
System.setProperty("fake.server.port", Integer.toString(server.getAddress().getPort()));
statement.evaluate();
} finally {
server.stop(0);
server = null;
System.clearProperty("fake.server.port");
}
}
};
}
@SuppressWarnings("unchecked")
@Override
public <T extends Closeable> T connect(String host, int port, PropertySet props, int loginTimeout) throws IOException {
try {
this.channel = AsynchronousSocketChannel.open();
//channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true);
this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024);
this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024);
Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port));
connectPromise.get();
} catch (CJCommunicationsException e) {
throw e;
} catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) {
throw new CJCommunicationsException(ex);
}
return (T) this.channel;
}
private SocketChannel createChannel() throws IOException {
final SocketChannel socketChannel = SocketChannel.open();
try {
socketChannel.configureBlocking(true);
final Socket socket = socketChannel.socket();
socket.setSoTimeout(timeoutMillis);
socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort()));
socket.setSoTimeout(timeoutMillis);
return socketChannel;
} catch (final Exception e) {
try {
socketChannel.close();
} catch (final Exception closeException) {
e.addSuppressed(closeException);
}
throw e;
}
}
@Before
public void setUp() throws Exception {
service = new FlushingService();
serverCtx = HttpServers.forAddress(localAddress(0))
.ioExecutor(ctx.ioExecutor())
.executionStrategy(noOffloadsStrategy())
.listenStreaming(service)
.toFuture().get();
InetSocketAddress serverAddr = (InetSocketAddress) serverCtx.listenAddress();
client = forSingleAddress(new NoopSD(serverAddr), serverAddr)
.disableHostHeaderFallback()
.ioExecutor(ctx.ioExecutor())
.executionStrategy(noOffloadsStrategy())
.unresolvedAddressToHost(InetSocketAddress::getHostString)
.buildStreaming();
conn = client.reserveConnection(client.get("/")).toFuture().get();
}
void addListenAddress(final String name, final InetSocketAddress socketAddress)
{
addresses.add(
new GuiceRsServerRuntimeInfo.ListenAddress()
{
@Override
public String getName()
{
return name;
}
@Override
public InetSocketAddress getSocketAddress()
{
return socketAddress;
}
});
}
@Override
public final AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
throws IOException
{
InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :
Net.checkAddress(local);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkListen(isa.getPort());
try {
begin();
synchronized (stateLock) {
if (localAddress != null)
throw new AlreadyBoundException();
NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
Net.bind(fd, isa.getAddress(), isa.getPort());
Net.listen(fd, backlog < 1 ? 50 : backlog);
localAddress = Net.localAddress(fd);
}
} finally {
end();
}
return this;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = e.getChannel();
log.info("PCC connected from {}", channel.getRemoteAddress());
address = channel.getRemoteAddress();
if (!(address instanceof InetSocketAddress)) {
throw new IOException("Invalid peer connection.");
}
inetAddress = (InetSocketAddress) address;
peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
// Wait for open message from pcc client
setState(ChannelState.OPENWAIT);
controller.peerStatus(peerAddr, PcepCfg.State.OPENWAIT.toString(), sessionId);
}
@Test
public void testSimpleHostUrl() throws Exception {
String serviceUrl = "pulsar://host1:6650";
resolver.updateServiceUrl(serviceUrl);
assertEquals(serviceUrl, resolver.getServiceUrl());
assertEquals(ServiceURI.create(serviceUrl), resolver.getServiceUri());
InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved("host1", 6650);
assertEquals(expectedAddress, resolver.resolveHost());
assertEquals(URI.create(serviceUrl), resolver.resolveHostUri());
String newServiceUrl = "pulsar://host2:6650";
resolver.updateServiceUrl(newServiceUrl);
assertEquals(newServiceUrl, resolver.getServiceUrl());
assertEquals(ServiceURI.create(newServiceUrl), resolver.getServiceUri());
InetSocketAddress newExpectedAddress = InetSocketAddress.createUnresolved("host2", 6650);
assertEquals(newExpectedAddress, resolver.resolveHost());
assertEquals(URI.create(newServiceUrl), resolver.resolveHostUri());
}
public SocketOrChannelConnectionImpl(ORB orb,
CorbaContactInfo contactInfo,
boolean useSelectThreadToWait,
boolean useWorkerThread,
String socketType,
String hostname,
int port)
{
this(orb, useSelectThreadToWait, useWorkerThread);
this.contactInfo = contactInfo;
try {
socket = orb.getORBData().getSocketFactory()
.createSocket(socketType,
new InetSocketAddress(hostname, port));
socketChannel = socket.getChannel();
if (socketChannel != null) {
boolean isBlocking = !useSelectThreadToWait;
socketChannel.configureBlocking(isBlocking);
} else {
// IMPORTANT: non-channel-backed sockets must use
// dedicated reader threads.
setUseSelectThreadToWait(false);
}
if (orb.transportDebugFlag) {
dprint(".initialize: connection created: " + socket);
}
} catch (Throwable t) {
throw wrapper.connectFailure(t, socketType, hostname,
Integer.toString(port));
}
state = OPENING;
}
/** Sets the required configurations for performing failover. */
public static void setFailoverConfigurations(MiniDFSCluster cluster,
Configuration conf, String logicalName, int nsIndex) {
InetSocketAddress nnAddr1 = cluster.getNameNode(2 * nsIndex).getNameNodeAddress();
InetSocketAddress nnAddr2 = cluster.getNameNode(2 * nsIndex + 1).getNameNodeAddress();
setFailoverConfigurations(conf, logicalName, nnAddr1, nnAddr2);
}
@Override
public Channel connect() {
final String ip = serviceInstance.getIp();
final int port = serviceInstance.getPort();
final ChannelFuture future = bootstrap.connect(new InetSocketAddress(ip, port));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (channelFuture.isSuccess()) {
log.debug("future callback, connect to {}:{} success, channel={}",
ip, port, channelFuture.channel());
// 发送clientName包到server
if (communicationOptions.getProtocol() instanceof ServerPushProtocol) {
sendClientNameToServer(future);
}
} else {
log.debug("future callback, connect to {}:{} failed due to {}",
ip, port, channelFuture.cause().getMessage());
}
}
});
future.syncUninterruptibly();
if (future.isSuccess()) {
return future.channel();
} else {
// throw exception when connect failed to the connection pool acquirer
log.error("connect to {}:{} failed, msg={}", ip, port, future.cause().getMessage());
throw new RpcException(future.cause());
}
}
public void start() {
log.debug("BGP Session Manager start.");
isShutdown = false;
ChannelFactory channelFactory = new NioServerSocketChannelFactory(
newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d", log)),
newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d", log)));
ChannelPipelineFactory pipelineFactory = () -> {
// Allocate a new session per connection
BgpSession bgpSessionHandler =
new BgpSession(BgpSessionManager.this);
BgpFrameDecoder bgpFrameDecoder =
new BgpFrameDecoder(bgpSessionHandler);
// Setup the processing pipeline
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder);
pipeline.addLast("BgpSession", bgpSessionHandler);
return pipeline;
};
InetSocketAddress listenAddress =
new InetSocketAddress(bgpPort);
serverBootstrap = new ServerBootstrap(channelFactory);
// serverBootstrap.setOptions("reuseAddr", true);
serverBootstrap.setOption("child.keepAlive", true);
serverBootstrap.setOption("child.tcpNoDelay", true);
serverBootstrap.setPipelineFactory(pipelineFactory);
try {
serverChannel = serverBootstrap.bind(listenAddress);
allChannels.add(serverChannel);
} catch (ChannelException e) {
log.debug("Exception binding to BGP port {}: ",
listenAddress.getPort(), e);
}
}
public static RaidProtocol createRaidnode(InetSocketAddress raidNodeAddr,
Configuration conf) throws IOException {
try {
return createRaidnode(createRPCRaidnode(raidNodeAddr, conf,
UnixUserGroupInformation.login(conf, true)));
} catch (LoginException e) {
throw (IOException)(new IOException().initCause(e));
}
}
@Test
public void shouldConvertRealEnrToDiscoveryPeer() throws Exception {
final String enr =
"-Iu4QMmfe-EkDnVX6k5i2LFTiDQ-q4-Cb1I01iRI-wbCD_r4Z8eujNCgZDmZXb1ZOPi1LfJaNx3Bd0QUK9wqBjwUXJQBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQO4btn3R6f6mZY_OeOxdrRenoYxCKLRReo6TnbY0JNRlIN0Y3CCIyiDdWRwgiMo";
final NodeRecord nodeRecord = NodeRecordFactory.DEFAULT.fromBase64(enr);
final DiscoveryPeer expectedPeer =
new DiscoveryPeer(
Bytes.fromHexString(
"0x03B86ED9F747A7FA99963F39E3B176B45E9E863108A2D145EA3A4E76D8D0935194"),
new InetSocketAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 9000),
Optional.of(Bytes.EMPTY));
assertThat(convertToDiscoveryPeer(nodeRecord)).contains(expectedPeer);
}
private HttpServer runContentSizeLyingHttpServer400(String path) {
final int port = 15999;
try {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext(path, new ContentSizeLyingHandler(400));
server.setExecutor(null);
server.start();
return server;
} catch (IOException ex) {
fail(ex.getMessage());
}
return null;
}
private static Optional<String> xForwardedFor(LiveHttpRequest request, HttpInterceptor.Context context) {
Optional<String> maybeClientAddress = context.clientAddress()
.map(InetSocketAddress::getHostString)
.map(hostName -> request
.header(X_FORWARDED_FOR)
.map(xForwardedFor -> xForwardedFor + ", " + hostName)
.orElse(hostName));
if (!maybeClientAddress.isPresent()) {
LOGGER.warn("No clientAddress in context url={}", request.url());
}
return maybeClientAddress;
}
/**
* Acts as an iterator, returning the address of each node in the list sequentially.
* Once all the list has been iterated, null will be returned for each subsequent query.
*
* @return InetSocketAddress - The address/port of the next node.
* @throws PeerDiscoveryException
*/
@Nullable
public InetSocketAddress getPeer() throws PeerDiscoveryException {
try {
return nextPeer();
} catch (UnknownHostException e) {
throw new PeerDiscoveryException(e);
}
}
@BeforeClass
public void setUp() throws Exception {
shouldRun = ensureInet6AddressFamily() && ensureIPv6OnLoopback();
server = HttpServer.create(new InetSocketAddress(0), 0);
server.createContext("/", ex -> {
ex.sendResponseHeaders(200, response.length());
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(ex.getResponseBody(), "UTF-8"))) {
writer.write(response);
}
ex.close();
});
server.start();
socks = new SocksServer(0, false);
socks.addUser("user", "pass");
socks.start();
Authenticator.setDefault(new Authenticator() {
@Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(
"user", "pass".toCharArray());
}
});
}
public static void main(String[] args) throws Exception {
Map<String, String> settings = System.getenv();
// When run from app-runner, you must use the port set in the environment variable APP_PORT
int port = Integer.parseInt(settings.getOrDefault("APP_PORT", "8081"));
// All URLs must be prefixed with the app name, which is got via the APP_NAME env var.
String appName = settings.getOrDefault("APP_NAME", "my-app");
String env = settings.getOrDefault("APP_ENV", "local"); // "prod" or "local"
boolean isLocal = "local".equals(env);
log.info("Starting " + appName + " in " + env + " on port " + port);
Server jettyServer = new Server(new InetSocketAddress("localhost", port));
jettyServer.setStopAtShutdown(true);
HandlerList handlers = new HandlerList();
// TODO: set your own handlers
handlers.addHandler(resourceHandler(isLocal));
// you must serve everything from a directory named after your app
ContextHandler ch = new ContextHandler();
ch.setContextPath("/" + appName);
ch.setHandler(handlers);
jettyServer.setHandler(ch);
try {
jettyServer.start();
} catch (Throwable e) {
log.error("Error on start", e);
System.exit(1);
}
log.info("Started app at http://localhost:" + port + ch.getContextPath());
jettyServer.join();
}
public SocketOrChannelConnectionImpl(ORB orb,
CorbaContactInfo contactInfo,
boolean useSelectThreadToWait,
boolean useWorkerThread,
String socketType,
String hostname,
int port)
{
this(orb, useSelectThreadToWait, useWorkerThread);
this.contactInfo = contactInfo;
try {
socket = orb.getORBData().getSocketFactory()
.createSocket(socketType,
new InetSocketAddress(hostname, port));
socketChannel = socket.getChannel();
if (socketChannel != null) {
boolean isBlocking = !useSelectThreadToWait;
socketChannel.configureBlocking(isBlocking);
} else {
// IMPORTANT: non-channel-backed sockets must use
// dedicated reader threads.
setUseSelectThreadToWait(false);
}
if (orb.transportDebugFlag) {
dprint(".initialize: connection created: " + socket);
}
} catch (Throwable t) {
throw wrapper.connectFailure(t, socketType, hostname,
Integer.toString(port));
}
state = OPENING;
}
@Test
public void testRTTPreference() {
NodeFactory.fillTable(node);
Collection<Key> localIds = node.localIDs();
RoutingTableEntry nonLocalFullBucket = node.table().stream().filter(e -> e.prefix.depth == 1).findAny().get();
Key newId = nonLocalFullBucket.prefix.createRandomKeyFromPrefix();
PingResponse rsp = buildResponse(newId, new InetSocketAddress(NodeFactory.generateIp(DHTtype.IPV6_DHT ,(byte)0x00), 1234));
node.recieved(rsp);
// doesn't get inserted because the replacement buckets only overwrite entries once every second and the main bucket is stable anyway
assertFalse(nonLocalFullBucket.getBucket().getEntries().stream().anyMatch(e -> e.getID().equals(newId)));
assertFalse(nonLocalFullBucket.getBucket().getReplacementEntries().stream().anyMatch(e -> e.getID().equals(newId)));
long now = System.currentTimeMillis();
RPCCall call = rsp.getAssociatedCall();
call.sentTime = now - 50;
call.responseTime = now;
node.recieved(rsp);
// main bucket accepts one RTT-based replacement for the youngest entry
assertTrue(nonLocalFullBucket.getBucket().getEntries().stream().anyMatch(e -> e.getID().equals(newId)));
Key anotherId = nonLocalFullBucket.prefix.createRandomKeyFromPrefix();
rsp = buildResponse(anotherId, new InetSocketAddress(NodeFactory.generateIp(DHTtype.IPV6_DHT, (byte)0x00), 1234));
call = rsp.getAssociatedCall();
call.sentTime = now - 50;
call.responseTime = now;
node.recieved(rsp);
// replacement bucket accepts RTT-based overwrite once main bucket is satisfied
assertTrue(nonLocalFullBucket.getBucket().getReplacementEntries().stream().anyMatch(e -> e.getID().equals(anotherId)));
}