【问题标题】:python socket - cant get sent data from javascriptpython socket - 无法从javascript获取发送的数据
【发布时间】:2016-05-22 18:37:28
【问题描述】:

我正在尝试让一个 javascript 程序向 python 套接字发送数据,但它没有接收到正确的数据。

我希望 python 打印 'aaaa'。

这是我的 javascript 代码:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {

    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    xhr = null;

  }
  return xhr;
}



var xhr = createCORSRequest('GET', "http://192.168.1.10:12345");


xhr.send("aaaa");

这是我的python代码:

import socket

s = socket.socket()
host = socket.gethostname()
port = 12345
BUFFER_SIZE = 1024
s.bind(('', port))

s.listen(5)
while True:
    c, addr = s.accept()
    print ('Got connection from', addr)
    c.send(bytes('Thank you for connecting','UTF-8'))
    data = c.recv(BUFFER_SIZE)
    print(data)
    c.close()

【问题讨论】:

  • 您是通过浏览器发送 javascript 吗?
  • 是的,我正在通过我的浏览器发送 javascript

标签: javascript python sockets python-3.x


【解决方案1】:
  1. 您正在执行 XMLHttpRequest,这是一个 HTTP 请求。但是你的 python 服务器根本不处理 HTTP 协议。处理 HTTP 意味着读取 HTTP 请求标头,根据标头中的信息读取正文并返回正确的 HTTP 响应。
  2. 您正在执行 HTTP GET 请求。 GET 请求不带任何负载,因此您添加的任何正文数据(即xhr.send("aaaa") 中的"aaaa")都将被忽略(意味着:不发送)。要发送 HTTP 正文,请使用 POST 等请求类型。

【讨论】:

    【解决方案2】:

    Steffen 的回答是正确的(至少在一般情况下 - 无法评论 JS 细节)。此外,独立验证应用程序的移动部分始终是一个好主意,这样您就可以缩小问题所在。

    您可以通过以下方式验证您的 python 服务器是否可以从命令行运行:

    1. 启动服务器
    2. 在另一个终端窗口中,使用 telnet 连接到它

      telnet localhost 12345

      (它将首先尝试使用 IPv6 连接,失败,然后回退到 IPv4)

    3. 您将看到您的欢迎消息返回给客户端。输入一些文字,然后按Enter

    4. 服务器将打印您的消息并关闭与客户端的连接。

    使用您的代码,它会如何查找客户端。我正在将文本meow 发送到服务器:

    margold@home-macbook ~ $ telnet 127.0.0.1 12345
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    Thank you for connectingmeow
    Connection closed by foreign host.
    

    对于服务器:

    margold@home-macbook ~ $ ./server.py
    ('Got connection from', ('127.0.0.1', 61148))
    meow
    

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 2016-08-07
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2018-06-16
      相关资源
      最近更新 更多