本文整理汇总了Java中java.net.SocketAddress类的典型用法代码示例。如果您正苦于以下问题:Java SocketAddress类的具体用法?Java SocketAddress怎么用?Java SocketAddress使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SocketAddress类属于java.net包,在下文中一共展示了SocketAddress类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.net.SocketAddress; //导入依赖的package包/类
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();
}
示例2: decode
import java.net.SocketAddress; //导入依赖的package包/类
@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;
}
示例3: open
import java.net.SocketAddress; //导入依赖的package包/类
@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;
}
示例4: decode
import java.net.SocketAddress; //导入依赖的package包/类
@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;
}
示例5: bind
import java.net.SocketAddress; //导入依赖的package包/类
/**
* 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;
}
示例6: sendAck
import java.net.SocketAddress; //导入依赖的package包/类
/**
* 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());
}
}
示例7: parseCommandResponse
import java.net.SocketAddress; //导入依赖的package包/类
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;
}
示例8: hasGoodReputation
import java.net.SocketAddress; //导入依赖的package包/类
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
}
示例9: decode
import java.net.SocketAddress; //导入依赖的package包/类
@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;
}
示例10: processRequestsWithBody
import java.net.SocketAddress; //导入依赖的package包/类
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);
}
示例11: Server
import java.net.SocketAddress; //导入依赖的package包/类
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();
}
示例12: testTryWithResourcesShouldCloseAllClustersButNotEventLoopAndTimerIfProvided
import java.net.SocketAddress; //导入依赖的package包/类
@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();
}
示例13: addLog
import java.net.SocketAddress; //导入依赖的package包/类
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;
}
示例14: getRemoteSocketAddress
import java.net.SocketAddress; //导入依赖的package包/类
/**
* 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;
}
}
示例15: decode
import java.net.SocketAddress; //导入依赖的package包/类
@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);
}
}