下面列出了java.nio.channels.DatagramChannel#bind() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void receive() throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while (selector.select() > 0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = it.next();
if (sk.isReadable()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf)
;
buf.flip();
System.out.println(new String(buf.array(), 0, buf.limit()));
buf.clear();
}
}
it.remove();
}
}
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
throws IOException {
final DatagramChannel dChannel = DatagramChannel.open();
dChannel.configureBlocking(false);
if (receiveBufferSize > 0) {
dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
if (actualReceiveBufSize < receiveBufferSize) {
LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to "
+ receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
+ "bytes. You may want to consider changing the Operating System's "
+ "maximum receive buffer");
}
}
dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
dChannel.bind(new InetSocketAddress(nicIPAddress, port));
return dChannel;
}
@Test
public void TestServer() throws Exception {
//接受组播和发送组播的数据报服务都要把组播地址添加进来
String host = "239.239.239.88";//多播地址
int port = 9998;
InetAddress group = InetAddress.getByName(host);
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.bind(new InetSocketAddress(port));
channel.join(group, Utils.getLocalNetworkInterface());
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketAddress sender = channel.receive(buffer);
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
System.out.println(new String(data));
}
@Override
protected AbstractSelectableChannel getChannel() throws IOException {
DatagramChannel c;
if (isWaitResponse()) {
c = DatagramChannelWithTimeouts.open();
((DatagramChannelWithTimeouts) c).setReadTimeout(getTimeoutAsInt());
} else {
c = DatagramChannel.open();
}
String bindAddress = getBindAddress();
if (bindAddress.isEmpty()) {
bindAddress = "0.0.0.0";
}
int adr = getBindPortAsInt();
c.bind(new InetSocketAddress(bindAddress, adr));
int port = Integer.parseInt(getPort());
c.connect(new InetSocketAddress(getHostName(), port));
return c;
}
public static MarketData open(NetworkInterface multicastInterface,
InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
long instrument) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(multicastGroup.getPort()));
channel.join(multicastGroup.getAddress(), multicastInterface);
channel.configureBlocking(false);
DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);
requestChannel.configureBlocking(false);
return new MarketData(channel, requestChannel, requestAddress, instrument);
}
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
throws IOException {
final DatagramChannel dChannel = DatagramChannel.open();
dChannel.configureBlocking(false);
if (receiveBufferSize > 0) {
dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
if (actualReceiveBufSize < receiveBufferSize) {
LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to "
+ receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
+ "bytes. You may want to consider changing the Operating System's "
+ "maximum receive buffer");
}
}
dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
dChannel.bind(new InetSocketAddress(nicIPAddress, port));
return dChannel;
}
@Test
public void receive() throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while (selector.select() > 0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = it.next();
if (sk.isReadable()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf);
buf.flip();
System.out.println(new String(buf.array(), 0, buf.limit()));
buf.clear();
}
}
it.remove();
}
}
/** Create UDP channel
*
* @param broadcast Support broadcast?
* @param port Port to use or 0 to auto-assign
* @return UDP channel
* @throws Exception on error
*/
public static DatagramChannel createUDP(boolean broadcast, int port) throws Exception
{
// Current use of multicast addresses works only with INET, not INET6
final DatagramChannel udp = DatagramChannel.open(StandardProtocolFamily.INET);
udp.configureBlocking(true);
if (broadcast)
udp.socket().setBroadcast(true);
udp.socket().setReuseAddress(true);
udp.bind(new InetSocketAddress(port));
return udp;
}
private static void test() throws Exception {
DatagramChannel dc = DatagramChannel.open();
InetAddress localHost = InetAddress.getLocalHost();
dc.bind(new InetSocketAddress(localHost, 0));
Server server = new Server(dc.getLocalAddress());
Thread serverThread = new Thread(server);
serverThread.start();
try {
InetSocketAddress isa = new InetSocketAddress(localHost, server.port());
dc.connect(isa);
ByteBuffer bb = ByteBuffer.allocateDirect(12);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(1).putLong(1);
bb.flip();
dc.write(bb);
bb.rewind();
dc.write(bb);
bb.rewind();
dc.write(bb);
Thread.sleep(2000);
serverThread.interrupt();
server.throwException();
} finally {
dc.close();
}
}
private synchronized DatagramChannel getChannel() throws IOException {
if (channel == null || !channel.isOpen()) {
if (shutdown.get()) {
throw new IllegalStateException("Channel has been shut down");
}
ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind to any-local before setting TTL
int port = group.getAddress().getPort();
if (protocolFamily == StandardProtocolFamily.INET) {
_channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
} else {
_channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
}
int timeToLive = group.getTimeToLive();
if (timeToLive != 1) {
_channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
}
for (NetworkInterface iface : networkInterfaces) {
_channel.join(group.getAddress().getAddress(), iface);
}
_channel.configureBlocking(false);
channel = _channel;
}
return channel;
}
@Test
public void testBlockSockets() throws Exception {
DatagramChannel channel1 = DatagramChannel.open();
channel1.configureBlocking(true);
// No empty datagram for connected socket
// https://bugs.openjdk.java.net/browse/JDK-8013175
// channel1.connect(bindAddress);
DatagramChannel channel2 = DatagramChannel.open();
channel2.configureBlocking(true);
channel2.bind(REFLECTOR_ADDRESS);
ByteBuffer bb = ByteBuffer.allocate(0);
bb.clear();
try {
bb.flip();
int sent = channel1.send(bb, REFLECTOR_ADDRESS);
Assert.assertEquals(0, sent);
Thread.sleep(100);
bb.clear();
InetSocketAddress address = (InetSocketAddress) channel2.receive(bb);
Assert.assertNotNull(address);
Assert.assertEquals(0, bb.position());
} finally {
NioUtils.close(channel2);
NioUtils.close(channel1);
}
}
/**
* Receive messages. Invoke the message listener on each message. Continue
* until a packet indicating the End of Session is received.
*
* @param multicastInterface the multicast interface
* @param multicastGroup the multicast group
* @param requestAddress the request address
* @param listener a message listener
* @throws IOException if an I/O error occurs
*/
public static void receive(NetworkInterface multicastInterface,
InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
MessageListener listener) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(multicastGroup.getPort()));
channel.join(multicastGroup.getAddress(), multicastInterface);
channel.configureBlocking(false);
DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);
requestChannel.configureBlocking(false);
StatusListener statusListener = new StatusListener();
try (Selector selector = Selector.open();
MoldUDP64Client client = new MoldUDP64Client(channel, requestChannel,
requestAddress, listener, statusListener)) {
SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ);
SelectionKey requestChannelKey = requestChannel.register(selector, SelectionKey.OP_READ);
while (statusListener.receive) {
while (selector.select() == 0);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
if (selectedKeys.contains(channelKey))
client.receive();
if (selectedKeys.contains(requestChannelKey))
client.receiveResponse();
selectedKeys.clear();
}
}
}
static DatagramChannel openClientChannel() throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.bind(null);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, loopbackInterface());
channel.join(multicastGroup(), loopbackInterface());
return channel;
}
/**
*
* @param port
* @param addr
* @return
* @throws Exception
*/
public static DatagramChannel createDatagramChannel(int port, InetAddress addr) throws Exception {
final DatagramChannel channel = DatagramChannel.open();
if (addr == null) {
channel.bind(new InetSocketAddress(port));
}
else {
channel.bind(new InetSocketAddress(addr, port));
}
return channel;
}
@SuppressWarnings("resource")
public static @Nullable SelectionKey openBroadcastChannel(@Nullable Selector selector, String logId,
int broadcastPort) throws IOException {
if (selector == null) {
return null;
}
DatagramChannel broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
.setOption(StandardSocketOptions.SO_BROADCAST, true);
broadcastChannel.configureBlocking(false);
LOGGER.debug("{} : Binding the broadcast channel on port {}", logId, broadcastPort);
broadcastChannel.bind(new InetSocketAddress(broadcastPort));
return broadcastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
private void run() throws IOException
{
final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
final DatagramChannel receiveChannel = DatagramChannel.open();
Common.init(receiveChannel);
receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));
final DatagramChannel sendChannel = DatagramChannel.open();
Common.init(sendChannel);
final Selector selector = Selector.open();
final IntSupplier handler =
() ->
{
try
{
buffer.clear();
receiveChannel.receive(buffer);
final long receivedSequenceNumber = buffer.getLong(0);
final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
buffer.clear();
buffer.putLong(receivedSequenceNumber);
buffer.putLong(receivedTimestamp);
buffer.flip();
sendChannel.send(buffer, sendAddress);
}
catch (final IOException ex)
{
ex.printStackTrace();
}
return 1;
};
receiveChannel.register(selector, OP_READ, handler);
final AtomicBoolean running = new AtomicBoolean(true);
SigInt.register(() -> running.set(false));
while (true)
{
while (selector.selectNow() == 0)
{
if (!running.get())
{
return;
}
}
final Set<SelectionKey> selectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext())
{
final SelectionKey key = iter.next();
if (key.isReadable())
{
((IntSupplier)key.attachment()).getAsInt();
}
iter.remove();
}
}
}
private void run() throws IOException
{
final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
final DatagramChannel receiveChannel = DatagramChannel.open();
Common.init(receiveChannel);
receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));
final DatagramChannel sendChannel = DatagramChannel.open();
Common.init(sendChannel);
final Selector selector = Selector.open();
final NioSelectedKeySet keySet = Common.keySet(selector);
final ToIntFunction<SelectionKey> handler =
(key) ->
{
try
{
buffer.clear();
receiveChannel.receive(buffer);
final long receivedSequenceNumber = buffer.getLong(0);
final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
buffer.clear();
buffer.putLong(receivedSequenceNumber);
buffer.putLong(receivedTimestamp);
buffer.flip();
sendChannel.send(buffer, sendAddress);
}
catch (final IOException ex)
{
ex.printStackTrace();
}
return 1;
};
receiveChannel.register(selector, OP_READ, null);
final AtomicBoolean running = new AtomicBoolean(true);
SigInt.register(() -> running.set(false));
while (true)
{
while (selector.selectNow() == 0)
{
if (!running.get())
{
return;
}
}
keySet.forEach(handler);
}
}
static MarketData open(String session, NetworkInterface multicastInterface,
InetSocketAddress multicastGroup,
InetSocketAddress requestAddress) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
channel.connect(multicastGroup);
MoldUDP64Server transport = new MoldUDP64Server(channel, session);
DatagramChannel requestChannel = DatagramChannel.open();
requestChannel.bind(requestAddress);
requestChannel.configureBlocking(false);
MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);
return new MarketData(transport, requestTransport);
}
static MarketReporting open(String session, NetworkInterface multicastInterface,
InetSocketAddress multicastGroup,
InetSocketAddress requestAddress) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
channel.connect(multicastGroup);
MoldUDP64Server transport = new MoldUDP64Server(channel, session);
DatagramChannel requestChannel = DatagramChannel.open();
requestChannel.bind(requestAddress);
requestChannel.configureBlocking(false);
MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);
return new MarketReporting(transport, requestTransport);
}
static DatagramChannel openServerRequestChannel() throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.bind(null);
return channel;
}