Python网络服务器错误

问题描述:

我正在使用基于python的web服务器,但我收到此错误消息。我对Python仍然很陌生,不确定我做错了什么!我使用http://blog.scphillips.com/posts/2012/12/a-simple-python-webserver/作为参考。Python网络服务器错误

Traceback (most recent call last): File "control.py", line 203, in <module> 
    app = TetheredDriveApp() File "control.py", line 77, in __init__ 
    match = re.match('GET /api\?action=(\d|[A-Z]+)\sHTTP/1', req) File "/usr/lib/python3.2/re.py", line 156, in match 
    return _compile(pattern, flags).match(string) TypeError: can't use a string pattern on a bytes-like object 

这里是我的相关代码...

import socket 
import re 

def __init__(self): 
    host = '' 
    port = 61338 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    sock.bind((host, port)) 
    sock.listen(1) 

    self.onConnect() 

    while True: 
     csock, caddr = sock.accept() 
     req = csock.recv(1024) 
     match = re.match('GET /api\?action=(\d|[A-Z]+)\sHTTP/1', req) 
     motionChange = False 
     if match: 
      action = match.group(1) 

      # KeyPress 
      if action == 'PP': 
      self.sendCommandASCII('128') 

     else: 
      csock.sendall("0") 
     csock.close() 
+0

请发布一个[简短,独立,正确的示例](http://sscce.org/),以便我们可以运行您的代码并轻松解决问题! –

+0

不需要道歉:)我会看看你的代码 –

这就是我认为正在发生的事情:当你从缓冲区接收输入(在req = csock.recv(1024) # get the request, 1kB max),它以字节为单位的形式到来。 re需要一个字符串。尝试match = re.match('GET /move\?a=(\d+)\sHTTP/1', req)之前的行req = str(req, encoding = 'utf-8'),然后查看您得到了多少。如果这不起作用,请尝试使用与utf-8不同的编码。

req = csock.recv(1024) 
req = str(req, encoding='utf-8') # encoding may need to be changed 
match = re.match('GET /api\?action=(\d|[A-Z]+)\sHTTP/1', req)