【问题标题】:Understanding and creating a protocol for Python理解和创建 Python 协议
【发布时间】:2017-02-10 17:45:01
【问题描述】:

我有关于如何使用 TCP/IP 二进制流 API 的文档。所附图像显示了该协议。我在 C# 中有一个工作示例。我想用 python 来代替,因为我不知道 c# 或 windows。

我假设我会使用 python 套接字,然后我必须发送 API 消息,有效负载查看此文档。

你能指出我正确的方向来使用 python 吗?

如何设置它以知道这是身份验证消息、0x21 并压缩数据等?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(u"{'username':'username', 'password':'password'}".encode('utf8'))

【问题讨论】:

  • 不确定是什么阻止了您?你懂 Python,你知道如何在 Python 中实现 TCP 通信吗?你有协议文档...
  • 我不是很了解,我不确定你如何设置编码、压缩等。我习惯于 http 帖子
  • 关于这两个您的文档说:“请注意,服务器将使用与发送客户端身份验证消息相同的内容”(不是确切的引用)。所以我会开始没有压缩和任何最适合你的(JSON/BSON)。如果可行,请继续。哦,它也是“UTF-8”:)
  • 您的标头必须根据文档从字节设置:1 字节版本,4 字节序列(大端)...也许这会有所帮助:stackoverflow.com/a/18311133/982149

标签: c# python protocols


【解决方案1】:

在 OSI 模型中,您至少在第 5 层(会话)上位于第 4 层(传输、TCP/IP、...)之上。有一些会话层协议的实现示例,例如http、ftp、... 即在http://github.com/python-git/python/blob/master/Lib/ftplib.py 或http://github.com/python-git/python/blob/master/Lib/httplib.py 中

因为你的协议包含 headers 也许 http 是更好的例子

要在 http 协议中使用 TCP/IP API,请参阅 http://www.stackoverflow.com/questions/8315209/sending-http-headers-with-python

import socket

sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()

print "Incoming:", adress
print client.recv(1024)
print

client.send('HTTP/1.0 200 OK\r\n')
client.send("Content-Type: text/html\r\n\r\n")
client.send('<html><body><h1>Hello World</body></html>')
client.close()

print "Answering ..."
print "Finished."

sock.close()

据我所知,您完全跳过了代码中的标头(版本、序列、类型、编码...),您必须在发送帧时添加它们

那就试试吧

self.socket.send(...headers...)
self.socket.send(u"{'username':'username', 'password':'password'}".encode('utf8')) // has to be send as JSON ???

另见http://www.stackoverflow.com/questions/22083359/send-tetx-http-over-python-socket

ftp 示例(无标题...)

    # Internal: send one line to the server, appending CRLF
    def putline(self, line):
    line = line + CRLF
    if self.debugging > 1: print '*put*', self.sanitize(line)
    self.sock.sendall(line)

另见 scapy

【讨论】:

    【解决方案2】:

    我尝试使用一次 tcp 协议。您可以在所有请求中发送授权值(用户名,密码)。以及带有它的其他数据 exp({'username':'username', 'password':'password','data':'value'})。有了这个目前没有任何数据标准。许多 tcp 客户端发送这样的数据 #A#:username;password;#D:value\n (A -authorization ,D -data), example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 2023-03-08
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      相关资源
      最近更新 更多