Created
November 20, 2013 14:37
-
-
Save Batschkoto/7564214 to your computer and use it in GitHub Desktop.
Minecraft-Ping client for 1.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package de.batschkoto.mcping; | |
import com.google.common.base.Charsets; | |
import io.netty.buffer.ByteBuf; | |
import io.netty.buffer.Unpooled; | |
import io.netty.channel.Channel; | |
import io.netty.channel.ChannelHandlerContext; | |
import io.netty.channel.SimpleChannelInboundHandler; | |
public class Handler extends SimpleChannelInboundHandler<ByteBuf> { | |
public Channel ch; | |
@Override | |
public void channelActive(ChannelHandlerContext ctx) throws Exception { | |
this.ch = ctx.channel(); | |
ByteBuf buf = Unpooled.buffer(); | |
this.writeVarInt(0x00, buf); | |
this.writeVarInt(4, buf); | |
this.writeString("localhost", buf); | |
buf.writeShort(25565); | |
this.writeVarInt(1, buf); | |
this.send(buf); | |
buf.clear(); | |
this.writeVarInt(0x00, buf); | |
this.send(buf); | |
} | |
@Override | |
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf msg) throws Exception { | |
System.out.println(readString(msg)); | |
this.ch.close(); | |
} | |
public synchronized void send(ByteBuf buf){ | |
ByteBuf out = Unpooled.buffer(); | |
this.writeVarInt(buf.readableBytes(), out); | |
out.writeBytes(buf); | |
this.ch.writeAndFlush(out); | |
} | |
public void writeString(String s, ByteBuf buf) | |
{ | |
byte[] b = s.getBytes( Charsets.UTF_8 ); | |
writeVarInt( b.length, buf ); | |
buf.writeBytes( b ); | |
} | |
public String readString(ByteBuf buf) | |
{ | |
int len = readVarInt( buf ); | |
byte[] b = new byte[ len ]; | |
buf.readBytes( b ); | |
return new String( b, Charsets.UTF_8 ); | |
} | |
public int readVarInt(ByteBuf input) | |
{ | |
int out = 0; | |
int bytes = 0; | |
byte in; | |
while ( true ) | |
{ | |
in = input.readByte(); | |
out |= ( in & 0x7F ) << ( bytes++ * 7 ); | |
if ( bytes > 32 ) | |
{ | |
throw new RuntimeException( "VarInt too big" ); | |
} | |
if ( ( in & 0x80 ) != 0x80 ) | |
{ | |
break; | |
} | |
} | |
return out; | |
} | |
public void writeVarInt(int value, ByteBuf output) | |
{ | |
int part; | |
while ( true ) | |
{ | |
part = value & 0x7F; | |
value >>>= 7; | |
if ( value != 0 ) | |
{ | |
part |= 0x80; | |
} | |
output.writeByte( part ); | |
if ( value == 0 ) | |
{ | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment