简体   繁体   English

如何通过 Python Socket 发送原始 XML 而不是字节数据?

[英]How to send raw XML instead of bytes data over Python Socket?

Is there any method for Socket of Python to deliver XML instead of bytes. Python 的 Socket 有什么方法可以传递 XML 而不是字节。 As the server side only recieves raw XML.由于服务器端只接收原始 XML。 I tried the code below but it raises attribute error, it asks for bytes instead of string.我尝试了下面的代码,但它引发了属性错误,它要求输入字节而不是字符串。 Any idea?任何的想法?

  import socket

  server_ip = "192.168.88.52"
  port = 2605

  socket_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  socket_obj.settimeout(5.0)

  try:
      socket_obj.connect((server_ip, port, ))
      command = '<SERVICE ID="TA"><TRACKID_GET></TRACKID_GET></SERVICE>'

      socket_obj.send(command)
      print(f"Successfully send the command")

      data = socket_obj.recv(4096)
      print(f"Received Response: {data}")
  except socket.timeout as e:
      print(f"Response TimeOut: {e}")
      socket_obj.close()
  except Exception as e:
      print(f"Failed to connect to the P1 server: {e}")

There is no such thing as "raw XML" (except as an abstract concept).没有“原始 XML”这样的东西(作为抽象概念除外)。

There is also no such thing as sending "text" over the network (or writing it into a file for that matter).也没有通过网络发送“文本”(或将其写入文件)这样的事情。

Whatever you want to send through your socket will have to be encoded into bytes using some encoding.无论您想通过套接字发送什么,都必须使用某种编码将其编码为字节。 Just .encode() will default to UTF-8, which will probably do fine here (until it probably won't).只是.encode()将默认为 UTF-8,这在这里可能会很好(直到它可能不会)。

Also, you'll probably want .sendall() to ensure everything has been sent.此外,您可能希望.sendall()确保所有内容都已发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM