我刚刚研究了乔·阿姆斯特朗的博客中的erlang示例,我对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,然后启动服务器(代码假设webserver运行在localhost:8888上)。
发布于 2010-01-28 10:48:54
对那些有兴趣的人来说,这是解决办法。
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的请求:
您可以查看文件这里的差异。本质上,我的问题是在发送/接收之前对字符串进行解码/编码的方式。有一个关于google代码的websocket模块正在为Apache工作,我用它来找出我哪里出了问题。
发布于 2010-08-08 08:46:30
谢谢你分享代码。在Windows中运行这段代码时遇到了一个问题。我觉得这可能对那些还在想的人有帮助。
现在对我来说效果很好。
发布于 2011-01-18 16:38:12
Eventlet内置了websocket支持,stargate是一个用于使用websocket与金字塔web框架:http://boothead.github.com/stargate/的包。
https://stackoverflow.com/questions/2153294
复制相似问题