pyCraft/docs/connecting.rst

61 lines
2.1 KiB
ReStructuredText
Raw Normal View History

2015-03-21 23:08:44 +01:00
Connecting to Servers
======================
2016-12-19 11:26:12 +01:00
.. module:: minecraft.networking.connection
2015-03-21 23:08:44 +01:00
2016-12-19 11:26:12 +01:00
Your primary dealings when connecting to a server will be with the Connection class
2015-03-21 23:08:44 +01:00
2016-12-19 11:26:12 +01:00
.. autoclass:: Connection
2015-03-21 23:08:44 +01:00
:members:
Writing Packets
2015-03-21 23:08:44 +01:00
~~~~~~~~~~~~~~~~~~~~
The packet class uses a lot of magic to work, here is how to use them.
2016-12-19 11:26:12 +01:00
Look up the particular packet you need to deal with, for this example
let's go with the ``KeepAlivePacket``
2015-03-21 23:08:44 +01:00
2016-12-19 11:26:12 +01:00
.. autoclass:: minecraft.networking.packets.KeepAlivePacket
:undoc-members:
2015-03-21 23:08:44 +01:00
:inherited-members:
2016-12-19 11:26:12 +01:00
:exclude-members: read, write, context, get_definition, get_id, id, packet_name, set_values
2015-03-21 23:08:44 +01:00
2016-12-19 11:26:12 +01:00
Pay close attention to the definition attribute, and how our class variable corresponds to
the name given from the definition::
2015-03-21 23:08:44 +01:00
packet = KeepAlivePacket()
packet.keep_alive_id = random.randint(0, 5000)
connection.write_packet(packet)
2016-12-19 11:26:12 +01:00
and just like that, the packet will be written out to the server.
It is possible to implement your own custom packets by subclassing
:class:`minecraft.networking.packets.Packet`. Read the docstrings and
follow the examples in packets.py for more details on how to do advanced tasks
like having a packet that is compatible across multiple protocol versions.
Listening for Certain Packets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Let's look at how to listen for certain packets, the relevant method being
2016-12-19 11:26:12 +01:00
.. automethod:: Connection.register_packet_listener
An example of this can be found in the ``start.py`` headless client, it is recreated here::
2016-12-19 11:26:12 +01:00
connection = Connection(options.address, options.port, auth_token=auth_token)
connection.connect()
def print_chat(chat_packet):
print "Position: " + str(chat_packet.position)
print "Data: " + chat_packet.json_data
2016-12-19 11:26:12 +01:00
from minecraft.networking.packets import ChatMessagePacket
connection.register_packet_listener(print_chat, ChatMessagePacket)
The field names ``position`` and ``json_data`` are inferred by again looking at the definition attribute as before
2016-12-19 11:26:12 +01:00
.. autoclass:: minecraft.networking.packets.ChatMessagePacket
:undoc-members:
:inherited-members:
2016-12-19 11:26:12 +01:00
:exclude-members: read, write, context, get_definition, get_id, id, packet_name, set_values