python read recv(1024)

时间:2015-12-12 13:24:43

标签: python sockets websocket

我在python中构建了一个简单的websocket服务器。

我设法用javascript连接到websocket,处理握手,从浏览器发送消息并在客户端上捕获它。

现在我必须从浏览器发送消息并在服务器中捕获它。我用这个:

s.send("asd")

并在服务器上

rec = conn.recv(1024)
print rec

现在这给了我一些无意义的角色。 我试过rec.decode(“utf-8”),同样废话 我尝试了repr(rec),它给了我一个像“\ x8 \ x2 ......... etc”

这样的字符串

我该如何阅读这些讯息?

2 个答案:

答案 0 :(得分:1)

    #!/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 Handshake\r\n"
  shake += "Upgrade: WebSocket\r\n" 
  shake += "Connection: Upgrade\r\n"
  shake += "WebSocket-Origin: %s\r\n" % (headers['Origin'])
  shake += "WebSocket-Location: ws://%s/\r\n" % (headers['Host'])
  shake += "Sec-WebSocket-Accept: "+key+"\r\n"
  shake += "WebSocket-Protocol: sample\r\n\r\n"

  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()

这是我的服务器

答案 1 :(得分:0)

您只是忘了在邮件中添加编码/解码

客户端:

s.send("asd".encode('utf-8'))

服务器端:

rec = conn.recv(1024).decode('utf8')
print rec