4 .. module:: minecraft.networking.connection
6 Your primary dealings when connecting to a server will be with the Connection class
8 .. autoclass:: Connection
14 The packet class uses a lot of magic to work, here is how to use them.
15 Look up the particular packet you need to deal with, for this example
16 let's go with the ``serverbound.play.KeepAlivePacket``
18 .. autoclass:: minecraft.networking.packets.serverbound.play.KeepAlivePacket
21 :exclude-members: read, write, context, get_definition, get_id, id, packet_name, set_values
23 Pay close attention to the definition attribute, and how our class variable corresponds to
24 the name given from the definition::
26 from minecraft.networking.packets import serverbound
27 packet = serverbound.play.KeepAlivePacket()
28 packet.keep_alive_id = random.randint(0, 5000)
29 connection.write_packet(packet)
31 and just like that, the packet will be written out to the server.
33 It is possible to implement your own custom packets by subclassing
34 :class:`minecraft.networking.packets.Packet`. Read the docstrings and in
35 packets.py and follow the examples in its subpackages for more details on
36 how to do advanced tasks like having a packet that is compatible across
37 multiple protocol versions.
39 Listening for Certain Packets
40 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42 Let's look at how to listen for certain packets, the relevant decorator being
44 A decorator can be used to register a packet listener:
46 .. autodecorator:: Connection.listener
50 connection = Connection(options.address, options.port, auth_token=auth_token)
53 from minecraft.networking.packets.clientbound.play import ChatMessagePacket
55 @connection.listener(ChatMessagePacket)
56 def print_chat(chat_packet):
57 print "Position: " + str(chat_packet.position)
58 print "Data: " + chat_packet.json_data
61 Altenatively, packet listeners can also be registered seperate from the function definition.
63 .. automethod:: Connection.register_packet_listener
65 An example of this can be found in the ``start.py`` headless client, it is recreated here::
67 connection = Connection(options.address, options.port, auth_token=auth_token)
70 def print_chat(chat_packet):
71 print "Position: " + str(chat_packet.position)
72 print "Data: " + chat_packet.json_data
74 from minecraft.networking.packets.clientbound.play import ChatMessagePacket
75 connection.register_packet_listener(print_chat, ChatMessagePacket)
77 The field names ``position`` and ``json_data`` are inferred by again looking at the definition attribute as before
80 .. autoclass:: minecraft.networking.packets.clientbound.play.ChatMessagePacket
83 :exclude-members: read, write, context, get_definition, get_id, id, packet_name, set_values