【发布时间】:2010-01-28 08:58:50
【问题描述】:
我刚刚研究了Joe Armstrong's blog 的 erlang websockets 示例。我对 erlang 还是很陌生,所以我决定用 python 编写一个简单的服务器来帮助我了解 websockets(并希望通过解释一些 erlang乔的代码)。我有两个问题:
1) 我从页面收到的数据包含一个“ÿ”作为最后一个字符。这不会出现在 erlang 版本中,我无法确定它来自哪里已修复 - 这是因为字符串以 utf-8 编码,而我没有对其进行解码
2) 我似乎正在从服务器发送数据(通过 websocket)——这可以通过查看 client.send() 产生的字节数来确认。但是页面上什么也没有出现。 已修复,我没有正确编码字符串
我已经把所有的代码here。这是我的 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 上运行)
【问题讨论】: