public static void main(String[] args) throws IOException { ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes()); DatagramChannel dgChannel = DatagramChannel.open(); for(int i = 0; i < targets.length; i++){ data.rewind(); SocketAddress sa = new InetSocketAddress(targets[i], port); System.out.println("-------------\nDG_Sending data:" + "\n remaining:" + data.remaining() + "\n position:" + data.position() + "\n limit:" + data.limit() + "\n capacity:" + data.capacity() + " bytes on DG channel to " + sa); try { int n = dgChannel.send(data, sa); System.out.println("DG_Sent " + n + " bytes"); } catch (IOException e) { //This regression test is to check vm crash only, so ioe is OK. e.printStackTrace(); } } dgChannel.close(); }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { if (msg instanceof Position) { Position position = (Position) msg; if (latitudeFactor != 0) { position.setLatitude(Math.abs(position.getLatitude()) * latitudeFactor); } if (longitudeFactor != 0) { position.setLongitude(Math.abs(position.getLongitude()) * longitudeFactor); } } return msg; }
@Override protected DatagramChannel open(SocketAddress localAddress) throws Exception { final DatagramChannel c = DatagramChannel.open(); boolean success = false; try { new NioDatagramSessionConfig(c).setAll(getSessionConfig()); c.configureBlocking(false); c.socket().bind(localAddress); c.register(selector, SelectionKey.OP_READ); success = true; } finally { if (!success) { close(c); } } return c; }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; QueryStringDecoder decoder = new QueryStringDecoder(request.getUri()); DeviceSession deviceSession = getDeviceSession( channel, remoteAddress, decoder.getParameters().get("UserName").get(0)); if (deviceSession == null) { return null; } Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0)); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS)); position.setValid(true); position.setLatitude(parser.nextDouble(0)); position.setLongitude(parser.nextDouble(0)); position.setAltitude(parser.nextDouble(0)); position.setSpeed(parser.nextDouble(0)); position.setCourse(parser.nextDouble(0)); if (channel != null) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); channel.write(response).addListener(ChannelFutureListener.CLOSE); } return position; }
/** * Binds the channel's socket to a local address. */ @Override public SctpChannel bind(SocketAddress local) throws IOException { synchronized (receiveLock) { synchronized (sendLock) { synchronized (stateLock) { ensureOpenAndUnconnected(); if (isBound()) SctpNet.throwAlreadyBoundException(); InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : Net.checkAddress(local); SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkListen(isa.getPort()); } Net.bind(fd, isa.getAddress(), isa.getPort()); InetSocketAddress boundIsa = Net.localAddress(fd); port = boundIsa.getPort(); localAddresses.add(isa); if (isa.getAddress().isAnyLocalAddress()) wildcard = true; } } } return this; }
/** * send a reply-acknowledgement (6,2,3), sends it doing a busy write, the * ACK is so small that it should always go to the buffer * * @param key * @param channel */ protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) { try { ByteBuffer buf = ByteBuffer.wrap(command); int total = 0; if (channel instanceof DatagramChannel) { DatagramChannel dchannel = (DatagramChannel) channel; // were using a shared channel, document says its thread safe // TODO check optimization, one channel per thread? while (total < command.length) { total += dchannel.send(buf, udpaddr); } } else { while (total < command.length) { total += channel.write(buf); } } if (log.isTraceEnabled()) { log.trace("ACK sent to " + ((channel instanceof SocketChannel) ? ((SocketChannel) channel).socket().getInetAddress() : ((DatagramChannel) channel).socket().getInetAddress())); } } catch (java.io.IOException x) { log.warn("Unable to send ACK back through channel, channel disconnected?: " + x.getMessage()); } }
private Position parseCommandResponse(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); int responseTextLength = buf.bytesBefore((byte) 0); if (responseTextLength < 0) { responseTextLength = CMD_RESPONSE_SIZE - 3; } position.set(Position.KEY_RESULT, buf.readBytes(responseTextLength).toString(StandardCharsets.UTF_8)); return position; }
private boolean hasGoodReputation(ChannelHandlerContext ctx) { SocketAddress socketAddress = ctx.channel().remoteAddress(); //TODO(mmarquez): and if not ??? if (socketAddress instanceof InetSocketAddress) { InetAddress address = ((InetSocketAddress)socketAddress).getAddress(); if (!peerScoringManager.hasGoodReputation(address)) { return false; } byte[] nid = channel.getNodeId(); NodeID nodeID = nid != null ? new NodeID(nid) : null; if (nodeID != null && !peerScoringManager.hasGoodReputation(nodeID)) { return false; } } return true; //TODO(mmarquez): ugly }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_STATUS, parser.next()); position.setTime(parser.nextDateTime()); position.setValid(parser.next().equals("A")); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); position.setSpeed(parser.nextDouble(0)); return position; }
private Collection<FullHttpResponse> processRequestsWithBody(HttpMethod method, SocketAddress remoteAddress, Tuple<String, CharSequence>... urisAndBodies) throws InterruptedException { Collection<HttpRequest> requests = new ArrayList<>(urisAndBodies.length); for (Tuple<String, CharSequence> uriAndBody : urisAndBodies) { ByteBuf content = Unpooled.copiedBuffer(uriAndBody.v2(), StandardCharsets.UTF_8); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uriAndBody.v1(), content); request.headers().add(HttpHeaderNames.HOST, "localhost"); request.headers().add(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json"); requests.add(request); } return sendRequests(remoteAddress, requests); }
public Server() throws IOException { ssc = SctpServerChannel.open().bind(null); java.util.Set<SocketAddress> addrs = ssc.getAllLocalAddresses(); if (addrs.isEmpty()) debug("addrs should not be empty"); serverAddr = (InetSocketAddress) addrs.iterator().next(); }
@Test public void testTryWithResourcesShouldCloseAllClustersButNotEventLoopAndTimerIfProvided() throws Exception { EventLoopGroup eventLoop = new DefaultEventLoopGroup(); Timer timer = new HashedWheelTimer(); BoundCluster cluster; MockClient client; try (Server server = Server.builder() .withAddressResolver(localAddressResolver) .withTimer(timer) .withEventLoopGroup(eventLoop, LocalServerChannel.class) .build()) { cluster = server.register(ClusterSpec.builder().withNodes(5)); BoundNode node = cluster.node(0); SocketAddress address = node.getAddress(); client = new MockClient(eventLoop); client.connect(address); } // event loop should not have been closed. assertThat(eventLoop.isShutdown()).isFalse(); // timer should not have since a custom one was not provided. cluster .getServer() .timer .newTimeout( timeout -> { // noop }, 1, TimeUnit.SECONDS); eventLoop.shutdownGracefully(0, 0, TimeUnit.SECONDS); timer.stop(); }
public QueryLog addLog( Frame frame, SocketAddress socketAddress, long timestamp, Optional<StubMapping> stubOption) { boolean isPrimed = false; if (stubOption.isPresent()) { StubMapping stub = stubOption.get(); isPrimed = !(stub instanceof InternalStubMapping); } QueryLog log = new QueryLog(frame, socketAddress, timestamp, isPrimed, stubOption); queryLog.add(log); return log; }
/** * Returns the address to which the socket is connected. * * @return ip address of the remote side of the connection or null if not * connected */ @Override SocketAddress getRemoteSocketAddress() { // a lot could go wrong here, so rather than put in a bunch of code // to check for nulls all down the chain let's do it the simple // yet bulletproof way try { return ((SocketChannel) sockKey.channel()).socket() .getRemoteSocketAddress(); } catch (NullPointerException e) { return null; } }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ChannelBuffer buf = (ChannelBuffer) msg; if (buf.getUnsignedByte(buf.readerIndex()) == 0x7e) { return decodeArMessage(channel, remoteAddress, buf); } else { return decodeMgMessage(channel, remoteAddress, buf); } }
private Object decodeTcp(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) throws Exception { if (buf.getUnsignedShort(0) > 0) { parseIdentification(channel, remoteAddress, buf); } else { buf.skipBytes(4); return parseData(channel, remoteAddress, buf, 0); } return null; }
/** * {@inheritDoc} * @org.apache.xbean.Property nestedType="java.net.SocketAddress" */ public final void setDefaultLocalAddresses(List<? extends SocketAddress> localAddresses) { if (localAddresses == null) { throw new IllegalArgumentException("localAddresses"); } setDefaultLocalAddresses((Iterable<? extends SocketAddress>) localAddresses); }
public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException { final int opaque = request.getOpaque(); try { final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null); this.responseTable.put(opaque, responseFuture); final SocketAddress addr = channel.remoteAddress(); channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } else { responseFuture.setSendRequestOK(false); } responseTable.remove(opaque); responseFuture.setCause(f.cause()); responseFuture.putResponse(null); PLOG.warn("send a request command to channel <" + addr + "> failed."); } }); RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis); if (null == responseCommand) { if (responseFuture.isSendRequestOK()) { throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis, responseFuture.getCause()); } else { throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr), responseFuture.getCause()); } } return responseCommand; } finally { this.responseTable.remove(opaque); } }
static Set<SocketAddress> getLocalAddresses(int fd) throws IOException { Set<SocketAddress> set = null; SocketAddress[] saa = getLocalAddresses0(fd); if (saa != null) { set = getRevealedLocalAddressSet(saa); } return set; }
/** * checks ban-lists, then white-lists, then space for the server. Returns null on success, or an error message */ public String allowUserToConnect(SocketAddress address, GameProfile profile) { if (this.bannedPlayers.isBanned(profile)) { UserListBansEntry userlistbansentry = (UserListBansEntry)this.bannedPlayers.getEntry(profile); String s1 = "You are banned from this server!\nReason: " + userlistbansentry.getBanReason(); if (userlistbansentry.getBanEndDate() != null) { s1 = s1 + "\nYour ban will be removed on " + DATE_FORMAT.format(userlistbansentry.getBanEndDate()); } return s1; } else if (!this.canJoin(profile)) { return "You are not white-listed on this server!"; } else if (this.bannedIPs.isBanned(address)) { UserListIPBansEntry userlistipbansentry = this.bannedIPs.getBanEntry(address); String s = "Your IP address is banned from this server!\nReason: " + userlistipbansentry.getBanReason(); if (userlistipbansentry.getBanEndDate() != null) { s = s + "\nYour ban will be removed on " + DATE_FORMAT.format(userlistipbansentry.getBanEndDate()); } return s; } else { return this.playerEntityList.size() >= this.maxPlayers && !this.bypassesPlayerLimit(profile) ? "The server is full!" : null; } }
@Override public InetSocketAddress getRemoteAddress() { SocketAddress remoteAddress = channel.remoteAddress(); if (!(remoteAddress instanceof InetSocketAddress)) { throw new ClientException(new RuntimeException("Get remote address error, should be InetSocketAddress")); } return (InetSocketAddress) remoteAddress; }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); position.setValid(parser.nextInt(0) == 1); position.setTime(parser.nextDateTime()); position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); position.setSpeed(parser.nextDouble(0)); position.setCourse(parser.nextDouble(0)); position.set(Position.KEY_RSSI, parser.nextDouble()); position.set(Position.KEY_EVENT, parser.nextInt(0)); position.set(Position.PREFIX_ADC + 1, parser.nextInt(0)); position.set(Position.KEY_BATTERY, parser.nextInt(0)); position.set(Position.KEY_INPUT, parser.next()); position.set(Position.KEY_STATUS, parser.next()); return position; }
@Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); position.setTime(parser.nextDateTime()); position.setLongitude(parser.nextDouble(0)); position.setLatitude(parser.nextDouble(0)); position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble(0))); position.setCourse(parser.nextDouble(0)); position.setAltitude(parser.nextDouble(0)); int satellites = parser.nextInt(0); position.setValid(satellites >= 3); position.set(Position.KEY_SATELLITES, satellites); position.set(Position.KEY_EVENT, parser.next()); position.set(Position.KEY_BATTERY_LEVEL, parser.nextInt(0)); position.set(Position.PREFIX_TEMP + 1, parser.next()); return position; }
public RpcInfo(RpcMessage header, ChannelBuffer data, ChannelHandlerContext channelContext, Channel channel, SocketAddress remoteAddress) { this.header = header; this.data = data; this.channel = channel; this.remoteAddress = remoteAddress; }
/** * Get cache statistics for all memcached hosts known to {@link MemcachedClientIF}. * * @return Statistics for all available hosts. */ @Override protected CacheStatistics[] getStatistics() { final Map<SocketAddress, Map<String, String>> allStats = memcachedClient.getStats(); final List<CacheStatistics> statsList = new ArrayList<>(); for (final Map.Entry<SocketAddress, Map<String, String>> entry : allStats.entrySet()) { final SocketAddress key = entry.getKey(); final Map<String, String> statsMap = entry.getValue(); if (!statsMap.isEmpty()) { final long size = Long.parseLong(statsMap.get("bytes")); final long capacity = Long.parseLong(statsMap.get("limit_maxbytes")); final long evictions = Long.parseLong(statsMap.get("evictions")); final String name; if (key instanceof InetSocketAddress) { name = ((InetSocketAddress) key).getHostName(); } else { name = key.toString(); } statsList.add(new SimpleCacheStatistics(size, capacity, evictions, name)); } } return statsList.toArray(new CacheStatistics[statsList.size()]); }
/** * {@inheritDoc} */ public SocketAddress getServiceAddress() { IoService service = getService(); if (service instanceof IoAcceptor) { return ((IoAcceptor) service).getLocalAddress(); } return getRemoteAddress(); }
/** * Connect to a remote node if appropriate * @param bootstrap the client bootstrap object * @param n the node to connect to */ protected void doNodeConnect(Node n) { if (!shutDown && n.getNodeId() < syncManager.getLocalNodeId()) { Short nodeId = n.getNodeId(); synchronized (connections) { NodeConnection c = connections.get(n.getNodeId()); if (c == null) { connections.put(nodeId, c = new NodeConnection()); } if (logger.isTraceEnabled()) { logger.trace("[{}->{}] Connection state: {}", new Object[]{syncManager.getLocalNodeId(), nodeId, c.state}); } if (c.state.equals(NodeConnectionState.NONE)) { if (logger.isDebugEnabled()) { logger.debug("[{}->{}] Attempting connection {} {}", new Object[]{syncManager.getLocalNodeId(), nodeId, n.getHostname(), n.getPort()}); } SocketAddress sa = new InetSocketAddress(n.getHostname(), n.getPort()); c.pendingFuture = clientBootstrap.connect(sa); c.pendingFuture.addListener(new ConnectCFListener(n)); c.state = NodeConnectionState.PENDING; } } } }
private FakeRestRequest(NamedXContentRegistry xContentRegistry, Map<String, List<String>> headers, Map<String, String> params, BytesReference content, Method method, String path, SocketAddress remoteAddress) { super(xContentRegistry, params, path, headers); this.content = content; this.method = method; this.remoteAddress = remoteAddress; }
private SendFailed(int assocId, SocketAddress address, ByteBuffer buffer, int errorCode, int streamNumber) { this.assocId = assocId; this.errorCode = errorCode; this.streamNumber = streamNumber; this.address = address; this.buffer = buffer; }
private void opnSvrSocket() { try { this.serverSocketVal = new ServerSocket(); // this.serverSocketVal.setSoTimeout(READ_TIMEOUT_MILLISECONDS); SocketAddress socksAddress = new InetSocketAddress(host, serverPortVal); this.serverSocketVal.bind(socksAddress, CONNECT_TIMEOUT_MILLISECONDS); } catch (IOException e) { throw new RuntimeException("Not able to open the port " + serverPortVal + " ", e); } }
@Override public void connect(SocketAddress remoteAddr) throws IOException { delegate.connect(remoteAddr); }
public SocketAddress getStoreHost() { return storeHost; }
@Override public ChannelFuture connect(SocketAddress socketAddress, ChannelPromise channelPromise) { return null; }
@Override public SctpChannel bind(SocketAddress local) throws IOException { throw new UnsupportedOperationException(message); }
public void setBornHost(SocketAddress bornHost) { this.bornHost = bornHost; }
@Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
@Override public SocketAddress localAddress() { return null; }
protected void onMessageEvent( Channel channel, SocketAddress remoteAddress, Object originalMessage, Object decodedMessage) { }
@Override public SocketAddress getLocalAddress() { return channel.getLocalAddress(); }
@Override protected void doBind(SocketAddress localAddress) throws Exception { doBind0(localAddress); }