private void doBind0(SocketAddress localAddress) throws Exception { if (PlatformDependent.javaVersion() >= 7) { SocketUtils.bind(javaChannel(), localAddress); } else { javaChannel().socket().bind(localAddress); } }
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new UdpClientHandler()); Channel ch = b.bind(0).sync().channel(); String UdpMsg = "this a message form client !"; logger.info("Client ===> : {}", UdpMsg); // Broadcast the QOTM request to port 8880. ch.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(UdpMsg, CharsetUtil.UTF_8), SocketUtils.socketAddress("localhost", PORT))).sync(); // UdpClientHandler 接收到服务器响应的消息时,会关闭 DatagramChannel (数据报通道) // 如果 DatagramChannel (数据报通道) 没有在 5秒内关闭,那么打印错误日志,并退出 if (!ch.closeFuture().await(5000)) { logger.error("Server response timed out."); } } finally { group.shutdownGracefully(); } }
@Override public IMessage onMessage(TF2Message.InitMessage message, MessageContext ctx) { try { TF2UdpClient.instance = new TF2UdpClient(SocketUtils.socketAddress(TF2UdpClient.addressToUse, message.port)); TF2UdpClient.playerId = message.id; TF2weapons.network.useUdp = false; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("setting "+message.value); // TF2weapons.proxy.playReloadSound(player,stack); return null; }
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf buffer = msg.content(); int plid = buffer.readShort(); int seq = buffer.readUnsignedShort(); int msgid = buffer.readByte(); if(msgid == (byte)-128) { server.outboundTargets.put((short) plid, SocketUtils.socketAddress(msg.sender().getAddress().getHostAddress(),msg.sender().getPort())); } else { EntityPlayerMP player = server.playerList.get((short)plid); 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(player.connection, Side.SERVER); handler.onMessage(message, context); } System.out.println("PacketFrom: "+msg.sender().getAddress()+ " "+msg.sender().getPort()+" "); }
@Override protected void onInit() { try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } address = SocketUtils.socketAddress( config.getValue("multiplayer.ip"), Integer.parseInt(System.getProperty("port", "" + config.getValue("multiplayer.port")))); connectionService.connect(address); eventQueue.setConnectionService(connectionService); }