如何使用Python将数据包发送到远程Minecraft Classic服务器? [英] How to Send Packets to a Remote Minecraft Classic Server in Python?

查看:112
本文介绍了如何使用Python将数据包发送到远程Minecraft Classic服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StackOverflow的好朋友.

Hello kind folks of StackOverflow.

我正在尝试创建一种可以连接到Minecraft Classic服务器,发布消息并可能进行构建的机器人".

I am trying to make a sort of 'bot' which can connect to a Minecraft Classic server, post messages and possibly build.

无论如何,我在理解如何使用python发送数据包以及如何正确编码它们方面遇到了一些麻烦.

Anyway, I'm having some trouble understanding how to send packets in python, and how to correctly encode them.

以下是我需要发送的数据包,我想发送玩家标识": http://www.minecraftwiki.net/wiki/Classic_server_protocol#Client_.E2.86.92_Server_packets 我知道我需要使用套接字,并且需要使用struct.pack,但是我该如何发送呢?

Here are the packets I need to send, I want to send the 'Player Identification' one: http://www.minecraftwiki.net/wiki/Classic_server_protocol#Client_.E2.86.92_Server_packets I know I need to be using sockets, and I need to be using struct.pack, but how exactly can I send it?

发送登录数据包的示例片段代码非常奇妙.

An example piece code that sends a login packet would be marvellous.

谢谢.

推荐答案

我会让事情滚滚而来:

import socket
import struct

username = "username_value"
verification_key = "verification_key"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # boilerplate
s.connect(("example.com", 1234))  # adjust accordingly

# now for the packet
# note that the String type is specified as having a length of 64, we'll pad that

packet = ""

packet += struct.pack("B", 1)  # packet type
packet += struct.pack("B", 7)  # protocol version
packet += "%-64s" % username  # magic!
packet += "%-64s" % verification_key
packet += struct.pack("B", 0)  # that unused byte, assuming a NULL byte here

# send what we've crafted
s.send(packet)

如果您从未使用过格式字符串,那么%-20s"可能对您来说很奇怪.本质上..

The "%-20s" may be weird for you if you've never used format strings. Essentially..

print "%s" % 5

..将打印出5 ..

.. would print out 5 ..

print "%10s" % 5

..会将输出填充为正好10个字符的宽度.但是它在右侧填充它们,我们希望在左侧填充-因此- ..

.. would pad the output to be exactly 10 characters in width. But it pads them on the right side, we want that padding on the left -- hence the - ..

print "%-10s" % s, "<this will be 9 spaces away from the '5'>"

..玩弄它.

如果不清楚,请告诉我.我喜欢你在做什么,让我想起了我的一个老项目.除了我没有像您那样整洁的协议规范,幸运的混蛋. ;)

If anything is unclear, let me know. I like what you're doing, reminds me of an old project of mine. Except that I didn't have a neat protocol specification like you did, lucky bastard. ;)

这篇关于如何使用Python将数据包发送到远程Minecraft Classic服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆