我用python构建了一个简单的websocket服务器。
我设法用javascript连接到websocket,处理握手,从浏览器发送消息,并在客户端上捕捉到它。
现在我必须从浏览器发送一条消息,并在服务器上捕获它。我使用这个:
s.send("asd")
并且在服务器上
rec = conn.recv(1024)
print rec
现在这给了我一些无厘头的角色。我试过rec.decode("utf-8"),也是胡说八道我尝试了repr(rec),它给了我一个字符串,比如"\x8\x2……etc"
我该如何阅读这些信息?
#!/usr/bin/env python
import socket, hashlib, base64, os
def parse_headers (data):
headers = {}
lines = data.splitlines()
for l in lines:
parts = l.split(": ", 1)
if len(parts) == 2:
headers[parts[0]] = parts[1]
headers['code'] = lines[len(lines) - 1]
return headers
def createKey (key):
cc = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
s = hashlib.sha1()
s.update(key+cc)
h = s.digest()
return str(base64.b64encode(h));
def createHandshake (data):
headers = parse_headers(data)
key = createKey(headers['Sec-WebSocket-Key'])
shake = "HTTP/1.1 101 Web Socket Protocol Handshakern"
shake += "Upgrade: WebSocketrn"
shake += "Connection: Upgradern"
shake += "WebSocket-Origin: %srn" % (headers['Origin'])
shake += "WebSocket-Location: ws://%s/rn" % (headers['Host'])
shake += "Sec-WebSocket-Accept: "+key+"rn"
shake += "WebSocket-Protocol: samplernrn"
return shake
def handshake (client):
data = client.recv(1024)
shake = createHandshake(data)
return client.send(shake)
def sendData(data, conn):
length = len(data)
if length <= 125:
ret = bytearray([129, length])
for byte in data.encode("utf-8"):
ret.append(byte)
conn.send(ret)
def sendRamUsed(conn):
sendData("ram-"+os.popen("free -k | grep Mem | awk '{print $3}'").read(), conn)
def start_server ():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 8000))
s.listen(5)
conn, addr = s.accept()
print 'Connection from:', addr
handshake(conn)
data = "Hello"
# sendData(os.popen("free -k | grep Mem | awk '{print $2}'").read(), conn)
while 1:
rec = conn.recv(1024)
sendRamUsed(conn)
start_server()
这是我的服务器
您只是忘记在消息上添加编码/解码
客户端:
s.send("asd".encode('utf-8'))
服务器端:
rec = conn.recv(1024).decode('utf8')
print rec