Joe 的 Erlang websocket 示例的 Python 示例
题
我刚刚完成了 erlang websockets 示例 乔·阿姆斯特朗的博客 我对 erlang 还很陌生,所以我决定用 python 编写一个简单的服务器,这将有助于教我有关 websockets 的知识(希望通过解释 joe 的代码来了解一些 erlang)。我有两个问题:
1)我从页面收到的数据包含“ÿ”作为最后一个字符。这没有出现在 erlang 版本中,我不知道它来自哪里 已修复 - 这是因为字符串以 utf-8 编码,而我没有解码它们
2)我似乎正在从服务器发送数据(通过 websocket) - 这可以通过查看 client.send() 生成的字节数来确认。但页面上什么也没有出现。 已修复,我没有正确编码字符串
我已经把所有的代码都贴出来了 这里. 。这是我的 python 版本,以防我遗漏任何明显的东西
import threading
import socket
def start_server():
tick = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 1234))
sock.listen(100)
while True:
print 'listening...'
csock, address = sock.accept()
tick+=1
print 'connection!'
handshake(csock, tick)
print 'handshaken'
while True:
interact(csock, tick)
tick+=1
def handshake(client, tick):
our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade: WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin: http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
shake = client.recv(255)
print shake
client.send(our_handshake)
def interact(client, tick):
data = client.recv(255)
print 'got:%s' %(data)
client.send("clock ! tick%d\r" % (tick))
client.send("out ! recv\r")
if __name__ == '__main__':
start_server()
对于那些没有运行过 joe 的示例但仍想提供帮助的人,您只需通过 Web 服务器提供 interact.html,然后启动您的服务器(代码假设 Web 服务器正在 localhost:8888 上运行)
解决方案
有关那些有兴趣谁这是溶液
import threading
import socket
def start_server():
tick = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 1234))
sock.listen(100)
while True:
print 'listening...'
csock, address = sock.accept()
tick+=1
print 'connection!'
handshake(csock, tick)
print 'handshaken'
while True:
interact(csock, tick)
tick+=1
def send_data(client, str):
#_write(request, '\x00' + message.encode('utf-8') + '\xff')
str = '\x00' + str.encode('utf-8') + '\xff'
return client.send(str)
def recv_data(client, count):
data = client.recv(count)
return data.decode('utf-8', 'ignore')
def handshake(client, tick):
our_handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"+"Upgrade: WebSocket\r\n"+"Connection: Upgrade\r\n"+"WebSocket-Origin: http://localhost:8888\r\n"+"WebSocket-Location: "+" ws://localhost:1234/websession\r\n\r\n"
shake = recv_data(client, 255)
print shake
#We want to send this without any encoding
client.send(our_handshake)
def interact(client, tick):
data = recv_data(client, 255)
print 'got:%s' %(data)
send_data(client, "clock ! tick%d" % (tick))
send_data(client, "out ! %s" %(data))
if __name__ == '__main__':
start_server()
修改为liwp的请求:
可以 rel="noreferrer">这里查看该文件的一个差异。基本上我的问题是方式我被解码/之前发送/接收编码的字符串。有一个的WebSocket模块上正在工作的Apache上,我用来找出谷歌代码我打算错。
其他提示
感谢您分享代码。我在 Windows 中运行此代码时遇到了一个问题。我认为这对于仍在思考的人可能会有所帮助。
我把空间弄紧了,这样它就变成了“升级:”WebSocket'
确保您的托管页面与来源匹配,在本例中为“http://本地主机:8888'
现在它对我来说工作得很好。
Eventlet有内置的WebSocket支持和星门是用于使用的WebSockets与金字塔web框架的软件包: HTTP:/ /boothead.github.com/stargate/