gpt4 book ai didi

javascript - Python 套接字问题 : How To Get Reliably POSTed data whatever the browser?

转载 作者:行者123 更新时间:2023-11-30 18:59:33 25 4
gpt4 key购买 nike

我用 socket 模块编写了 Python+Ajax 小程序(在最后列出)来研究异步通信的 COMET 概念。

我的想法是允许浏览器通过我的 python 程序相互实时发送消息。

诀窍是让“GET messages/...”连接打开,等待消息回复。

我的问题主要在于我通过 socket.recv 所拥有的可靠性...

当我从 Firefox 发布时,它运行良好。

当我从 Chrome 或 IE 发布时,我在 Python 中获得的“数据”是空的。

有人知道浏览器之间的这个问题吗?

某些浏览器是否注入(inject)了一些 EOF 或其他字符以终止接收“recv”?

这个问题有什么已知的解决方案吗?

Python 中的 server.py:

 import socket
connected={}
def inRequest(text):
content=''
if text[0:3]=='GET':
method='GET'
else:
method='POST'
k=len(text)-1
while k>0 and text[k]!='\n' and text[k]!='\r':
k=k-1
content=text[k+1:]
text=text[text.index(' ')+1:]
url=text[:text.index(' ')]
return {"method":method,"url":url,"content":content}

mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 80 ) )
mySocket.listen ( 10 )
while True:
channel, details = mySocket.accept()
data=channel.recv(4096)
req=inRequest(data)
url=req["url"]
if url=="/client.html" or url=="/clientIE.html":
f=open('C:\\async\\'+url)
channel.send ('HTTP/1.1 200 OK\n\n'+f.read())
f.close()
channel.close()
elif '/messages' in url:
if req["method"]=='POST':
target=url[10:]
if target in connected:
connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"])
print req["content"]+" sent to "+target
connected[target].close()
channel.close()
elif req["method"]=='GET':
user=url[10:]
connected[user]=channel
print user+' is connected'

HTML+Javascript中的client.html:

<html>
<head>
<script>
var user=''
function post(el) {
if (window.XMLHttpRequest) {
var text=el.value;
var req=new XMLHttpRequest();
el.value='';
var target=document.getElementById('to').value
}
else if (window.ActiveXObject) {
var text=el.content;
var req=new ActiveXObject("Microsoft.XMLHTTP");
el.content='';
}
else
return;
req.open('POST','messages/'+target,true)
req.send(text);
}
function get(u) {
if (user=='')
user=u.value
var req=new XMLHttpRequest()
req.open('GET','messages/'+user,true)
req.onload=function() {
var message=document.createElement('p');
message.innerHTML=req.responseText;
document.getElementById('messages').appendChild(message);
get(user);
}
req.send(null)
}
</script>
</head>
<body>
<span>From</span>
<input id="user"/>
<input type="button" value="sign in" onclick="get(document.getElementById('user'))"/>
<span>To</span>
<input id="to"/>
<span>:</span>
<input id="message"/>

<input type="button" value="post" onclick="post(document.getElementById('message'))"/>
<div id="messages">
</div>
</body>
</html>

最佳答案

你的问题是

  • 您的 TCP 套接字处理没有像它应该的那样读取
  • 您的 http 处理不完整

我推荐以下讲座:

请参阅下面的示例,了解可以处理帖子的工作 http 服务器

index = '''
<html>
<head>
</head>
<body>
<form action="/" method="POST">
<textarea name="foo"></textarea>
<button type="submit">post</button>
</form>
<h3>data posted</h3>
<div>
%s
</div>
</body>
</html>
'''

bufsize = 4048
import socket
import re
from urlparse import urlparse

class Headers(object):
def __init__(self, headers):
self.__dict__.update(headers)

def __getitem__(self, name):
return getattr(self, name)

def get(self, name, default=None):
return getattr(self, name, default)

class Request(object):
header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M)

def __init__(self, sock):
header_off = -1
data = ''
while header_off == -1:
data += sock.recv(bufsize)
header_off = data.find('\r\n\r\n')
header_string = data[:header_off]
self.content = data[header_off+4:]

lines = self.header_re.findall(header_string)
self.method, path = lines.pop(0)
path, protocol = path.split(' ')
self.headers = Headers(
(name.lower().replace('-', '_'), value)
for name, value in lines
)

if self.method in ['POST', 'PUT']:
content_length = int(self.headers.get('content_length', 0))
while len(self.content) < content_length:
self.content += sock.recv(bufsize)

self.query = urlparse(path)[4]

acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1,
)
acceptor.bind(('', 2501 ))
acceptor.listen(10)

if __name__ == '__main__':
while True:
sock, info = acceptor.accept()
request = Request(sock)
sock.send('HTTP/1.1 200 OK\n\n' + (index % request.content) )
sock.close()

关于javascript - Python 套接字问题 : How To Get Reliably POSTed data whatever the browser?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/167426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com