最近、私はpython write websocketサーバーを使用し、ハンドシェイクはOKで、サーバーはクライアントからのメッセージを受け入れることができますが、サーバーがクライアントにメッセージを送信すると、サーバーは壊れたパイプのようなエラーに遭遇します。コードを徹底的にチェックして、道が分からないので誰か助けてくれませんか?これが私のサーバーコードです。前もって感謝します!
def SendData(pData, client, add):
if(pData == False):
return False
else:
#pData = str(pData)
pData = pData.encode("utf-8")
token = "\x81"
length = len(pData)
if length < 126:
token += struct.pack("B", length)
elif length <= 0xFFFF:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
pData = '%s%s' % (token, pData)
if client is not None:
#client.sendto(pData, add)
client.send(pData)
time.sleep(0.5)
return True
def RecvData(nNum, client):
try:
pData = client.recv(nNum)
if not len(pData):
return False
except:
return False
else:
code_length = ord(pData[1]) & 127
if code_length == 126:
masks = pData[4:8]
data = pData[8:]
elif code_length == 127:
masks = pData[10:14]
data = pData[14:]
else:
masks = pData[2:6]
data = pData[6:]
raw_str = ""
i = 0
for d in data:
raw_str += chr(ord(d) ^ ord(masks[i%4]))
i += 1
return raw_str
class WebSocket(threading.Thread):
def __init__(self, conn, remote, path="/"):
threading.Thread.__init__(self)
self.conn = conn
self.remote = remote
self.path = path
self.buffer = ""
def generate_key(self, raw_key):
return base64.b64encode(hashlib.sha1(raw_key.replace(" ", "")+\
'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest())
def run(self):
print 'Socket Start!'
headers = {}
self.handshaken = False
while True:
if self.handshaken == False:
print 'Socket Start Handshaken with %s!' % str(self.remote)
self.buffer += self.conn.recv(1024)
if self.buffer.find('\r\n\r\n') != -1:
header, data = self.buffer.split('\r\n\r\n', 1)
for line in header.split("\r\n")[1:]:
key, value = line.split(":", 1)
headers[key] = value
headers["Location"] = 'ws://%s%s' %\
(headers["Host"].replace(" ", ""), self.path)
key = self.generate_key(headers["Sec-WebSocket-Key"])
print key
handshake = 'HTTP/1.1 101 Switching Protocols\r\n\
Upgrade: websocket\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Accept: %s\r\n\
Sec-WebSocket-Origin: null\r\n\
Sec-WebSocket-Location: %s\r\n\r\n\
' %(key, headers["Location"])
print handshake
self.conn.send(handshake)
self.handshaken = True
print 'Socket Handshaken with %s success!' % \
str(self.remote)
else:
receive = RecvData(64, self.conn)
print type(receive)
print receive
time.sleep(0.5)
#self.conn.send('hello')
SendData('This is from server!', self.conn, self.remote)
receive = ""
class WebSocketServer(object):
def __init__(self):
self.socket = None
def begin(self):
print "WebSocketServer Ready!"
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(("192.168.71.128", 9876))
self.socket.listen(50)
while True:
conn, add = self.socket.accept()
newSocket = WebSocket(conn, add)
newSocket.run()
if __name__ == "__main__":
server = WebSocketServer()
server.begin()