本文整理汇总了Java中io.netty.channel.socket.DatagramPacket类的典型用法代码示例。如果您正苦于以下问题:Java DatagramPacket类的具体用法?Java DatagramPacket怎么用?Java DatagramPacket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
DatagramPacket类属于io.netty.channel.socket包,在下文中一共展示了DatagramPacket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: channelRead0
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
ByteBuf buffer = msg.content();
int seq = buffer.readUnsignedShort();
int msgid = buffer.readByte();
IMessage message = TF2weapons.network.messages[msgid].newInstance();
//buffer.discardReadBytes();
message.fromBytes(buffer);
IMessageHandler<IMessage, IMessage> handler = TF2weapons.network.handlerList.get(message.getClass());
if(constr == null) {
constr =MessageContext.class.getDeclaredConstructor(INetHandler.class, Side.class);
constr.setAccessible(true);
}
MessageContext context = constr.newInstance(Minecraft.getMinecraft().player.connection, Side.CLIENT);
handler.onMessage(message, context);
System.out.println("PacketFrom: "+msg.sender().getAddress()+ " "+msg.sender().getPort()+" ");
}
示例2: channelRead
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof DatagramPacket) {
// Get packet and sender data
DatagramPacket datagram = (DatagramPacket) msg;
InetSocketAddress sender = datagram.sender();
RakNetPacket packet = new RakNetPacket(datagram);
// If an exception happens it's because of this address
this.causeAddress = sender;
// Handle the packet and release the buffer
client.handleMessage(packet, sender);
datagram.content().readerIndex(0); // Reset position
client.getListener().handleNettyMessage(datagram.content(), sender);
datagram.content().release(); // No longer needed
// No exceptions occurred, release the suspect
this.causeAddress = null;
}
}
示例3: createListenerHandler
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
private SimpleChannelInboundHandler<DatagramPacket> createListenerHandler(SeedNode thisNode, ByteBuf seedNodeInfo) {
return new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
ByteBuf buf = msg.content();
if (buf.readableBytes() > 4 && buf.readInt() == Utils.MAGIC_BYTES) {
MessageTYpe msgType = MessageTYpe.values()[buf.readByte()];
if (msgType == MessageTYpe.DISCOVERY) {
String cluster = decodeUtf(buf);
InetSocketAddress address = decodeAddress(buf);
if (thisNode.cluster().equals(cluster) && !address.equals(thisNode.address())) {
onDiscoveryMessage(address);
DatagramPacket response = new DatagramPacket(seedNodeInfo.copy(), msg.sender());
ctx.writeAndFlush(response);
}
}
}
}
};
}
示例4: channelActive
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Creates the client request
RtMessage msg = client.createRequest();
// Encodes the request for network transmission
ByteBuf encodedMsg = RtWire.toWire(msg);
// Sends the request to the Roughtime server
ctx.writeAndFlush(new DatagramPacket(encodedMsg, addr))
.addListener(fut -> {
if (!fut.isSuccess()) {
System.out.println("Send failed " + fut.cause().getMessage());
}
});
}
示例5: sendToAll
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
public void sendToAll(IMessage message)
{
if(useUdp && discriminators.containsKey(message.getClass())) {
for (EntityPlayer player : TF2weapons.server.getPlayerList().getPlayers()) {
InetSocketAddress address=TF2weapons.udpServer.outboundTargets.get(player.getCapability(TF2weapons.PLAYER_CAP, null).udpServerId);
if(address != null) {
ByteBuf buffer = Unpooled.buffer();
buffer.writeShort(0);
buffer.writeByte(discriminators.get(message.getClass()));
message.toBytes(buffer);
DatagramPacket packet = new DatagramPacket(buffer, address);
TF2weapons.udpServer.channel.writeAndFlush(packet);
}
else {
super.sendTo(message, (EntityPlayerMP) player);
}
}
}
else {
super.sendToAll(message);
}
}
示例6: sendTo
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
public void sendTo(IMessage message, EntityPlayerMP player)
{
if(useUdp && discriminators.containsKey(message.getClass())) {
InetSocketAddress address=TF2weapons.udpServer.outboundTargets.get(player.getCapability(TF2weapons.PLAYER_CAP, null).udpServerId);
if (address != null) {
ByteBuf buffer = Unpooled.buffer();
buffer.writeShort(0);
buffer.writeByte(discriminators.get(message.getClass()));
message.toBytes(buffer);
DatagramPacket packet = new DatagramPacket(buffer, address);
TF2weapons.udpServer.channel.writeAndFlush(packet);
}
}
else {
super.sendTo(message, player);
}
}
示例7: sendToServer
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
public void sendToServer(IMessage message)
{
if(useUdp && TF2UdpClient.instance != null && discriminators.containsKey(message.getClass())) {
InetSocketAddress address=TF2UdpClient.instance.address;
//System.out.println("Addr: "+address);
if (address != null) {
ByteBuf buffer = Unpooled.buffer();
buffer.writeShort(TF2UdpClient.playerId);
buffer.writeShort(0);
buffer.writeByte(discriminators.get(message.getClass()));
message.toBytes(buffer);
DatagramPacket packet = new DatagramPacket(buffer, address);
TF2UdpClient.instance.channel.writeAndFlush(packet);
}
}
else {
super.sendToServer(message);
}
}
示例8: main
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
EventLoopGroup loopGroup = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(loopGroup).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelProverbClientHandler());
Channel ch = b.bind(0).sync().channel();
//向网段内所有的机器广播UDP消息
ch.writeAndFlush(
new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", CharsetUtil.UTF_8),
new InetSocketAddress("255.255.255.255", port))).sync();
//客户端等待15s接受服务端的应答消息,然后退出释放资源
if(!ch.closeFuture().await(15000)){
System.out.println("查询超时");
}
}finally{
loopGroup.shutdownGracefully();
}
}
示例9: send
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
public void send(ByteBuf msg) throws Exception
{
byte[] arr = msg.array();
byte[] buf = new byte[arr.length + id.length];
System.arraycopy(id, 0, buf, 0, id.length);
System.arraycopy(arr, 0, buf, id.length, arr.length);
ByteBuf bbuf = Unpooled.wrappedBuffer(buf);
if (debug && logger != null)
logger.info("discovery send " + new String(bbuf.array()));
datagramChannel.writeAndFlush(
new DatagramPacket(bbuf, multicastAddress)).sync();
// datagramChannel.writeAndFlush(buf, multicastAddress);
}
示例10: initialize
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
/**
* Initializes this socket and binds its internal udp socket to a free port.
* If the socket is already initialized any invocation of this method will
* result in an IllegalStateException.
*
* @throws SocketException Thrown in case the socket could not be initialized
*/
public void initialize() throws SocketException {
if ( this.isInitialized() ) {
throw new IllegalStateException( "Cannot re-initialized ClientSocket" );
}
this.udpSocket = new Bootstrap();
this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() );
this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class );
this.udpSocket.handler( new ChannelInboundHandlerAdapter() {
@Override
public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception {
io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg;
PacketBuffer content = new PacketBuffer( packet.content() );
InetSocketAddress sender = packet.sender();
if ( !receiveDatagram( sender, content ) ) {
// Push datagram to update queue:
handleDatagram( sender, content, System.currentTimeMillis() );
}
}
} );
try {
this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000, 65000 ) ).sync().channel();
} catch ( InterruptedException e ) {
SocketException exception = new SocketException( "Could not bind to socket" );
exception.initCause( e );
throw exception;
}
this.afterInitialize();
}
示例11: encode
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
protected void encode(ChannelHandlerContext ctx, PacketWrapper msg, List<Object> out) throws Exception {
ctx.attr(PipelineUtil.ADDRESS_ATTRIBUTE).set(msg.getRecipient());
if (msg.getPacket().getType().isRaw()) {
ctx.write(msg.getPacket());
return;
}
PacketRaknetOutCustomPacket.writeMany(ctx, msg).forEach(outgoing -> {
ByteBuf buffer = outgoing.getBuffer();
if (PocketEncoder.dump) {
PocketServer.getInstance().getLogger().debug("Encoded: {}", ByteBufUtil.hexDump(buffer).toUpperCase());
}
Consumer<Session> receipt = msg.getAckReceipt();
if (receipt != null) {
Session session = PocketServer.getInstance().getSessions().get(msg.getRecipient());
session.addAckReceipt(outgoing.getSequenceNumber(), receipt);
}
out.add(new DatagramPacket(buffer, msg.getRecipient()));
});
}
示例12: channelRead0
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
channel = ctx.channel();
sender = msg.sender();
ByteBuf content = msg.content();
int methodID = content.readInt();
int invID = content.readInt();
int argCount = content.readInt();
Object[] args = new Object[argCount];
for(int i = 0; i < argCount; i++) {
Class<?> clazz = Class.forName(readString(content));
args[i] = gson.fromJson(readString(content), clazz);
}
provider.invoke(methodID, invID, args);
}
示例13: sendInvocationResult
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
public void sendInvocationResult(int invocationID, Object result) {
ByteBuf buf = Unpooled.buffer();
buf.writeInt(invocationID);
String className = result == null ? Void.class.getCanonicalName() : result.getClass().getCanonicalName();
writeString(buf, className);
if(result instanceof ByteBuf) {
ByteBuf res = (ByteBuf) result;
buf.writeBytes(res);
} else {
String json = gson.toJson(result);
writeString(buf, json);
}
DatagramPacket msg = new DatagramPacket(buf, sender);
channel.writeAndFlush(msg);
}
示例14: decode
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
//Create our response packet from the datagram we received
final MasterServerResponsePacket packet = builder.construct(msg.content());
if (packet != null) {
final MasterServerResponse response = new MasterServerResponse();
if (response != null) {
response.setSender(msg.sender());
response.setRecipient(msg.recipient());
response.setResponsePacket(packet);
log.debug("Receiving Data '{}' from '{}' using Channel Id: {}", response.getClass().getSimpleName(), ctx.channel().remoteAddress(), ctx.channel().id());
//Pass the message back to the messenger
responseCallback.accept(response, null);
return;
}
}
throw new IllegalStateException("No response packet found for the incoming datagram");
}
示例15: decode
import io.netty.channel.socket.DatagramPacket; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
//Create our response packet from the datagram we received
final SourceResponsePacket packet = builder.construct(msg.content());
if (packet != null) {
try {
SourceServerResponse response = SourceResponseFactory.createResponseFrom(packet);
if (response != null) {
response.setSender(msg.sender());
response.setRecipient(msg.recipient());
response.setResponsePacket(packet);
log.debug("Receiving Data '{}' from '{}' using Channel Id: {}", response.getClass().getSimpleName(), ctx.channel().remoteAddress(), ctx.channel().id());
//Pass the message back to the messenger
responseHandler.accept(response, null);
return;
}
} catch (Exception e) {
responseHandler.accept(null, new AsyncGameLibCheckedException("Error while decoding source query response", e));
}
}
throw new NoResponseFoundForPacket("Could not find a response handler for the received datagram packet", packet);
}