当前位置: 首页>>代码示例>>Java>>正文


Java DatagramPacket类代码示例

本文整理汇总了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()+" ");
	
}
 
开发者ID:rafradek,项目名称:Mods,代码行数:21,代码来源:UdpChannelHandlerClient.java

示例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;
    }
}
 
开发者ID:KernelFreeze,项目名称:BedrockProxy,代码行数:22,代码来源:RakNetClientHandler.java

示例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);
                    }
                }
            }
        }
    };
}
 
开发者ID:hekate-io,项目名称:hekate,代码行数:26,代码来源:MulticastSeedNodeProvider.java

示例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());
        }
      });
}
 
开发者ID:int08h,项目名称:nearenough,代码行数:17,代码来源:NettyClient.java

示例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);
    }
}
 
开发者ID:rafradek,项目名称:Mods,代码行数:24,代码来源:TF2NetworkWrapper.java

示例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);
    }
}
 
开发者ID:rafradek,项目名称:Mods,代码行数:18,代码来源:TF2NetworkWrapper.java

示例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);
    }
}
 
开发者ID:rafradek,项目名称:Mods,代码行数:20,代码来源:TF2NetworkWrapper.java

示例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();
	}
	
}
 
开发者ID:hdcuican,项目名称:java_learn,代码行数:22,代码来源:ChineseProverbClient.java

示例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);
}
 
开发者ID:yajsw,项目名称:yajsw,代码行数:19,代码来源:MulticastEndpoint.java

示例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();
}
 
开发者ID:GoMint,项目名称:jRakNet,代码行数:40,代码来源:ClientSocket.java

示例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()));
    });
}
 
开发者ID:PocketServer,项目名称:PocketServer,代码行数:21,代码来源:PocketWrapperEncoder.java

示例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);
}
 
开发者ID:thilokru,项目名称:Controller-Support,代码行数:19,代码来源:NetworkHandler.java

示例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);
}
 
开发者ID:thilokru,项目名称:Controller-Support,代码行数:18,代码来源:NetworkHandler.java

示例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");
}
 
开发者ID:ribasco,项目名称:async-gamequery-lib,代码行数:19,代码来源:MasterServerPacketDecoder.java

示例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);
}
 
开发者ID:ribasco,项目名称:async-gamequery-lib,代码行数:24,代码来源:SourceQueryPacketDecoder.java


注:本文中的io.netty.channel.socket.DatagramPacket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。