2015-01-21 46 views
2

我需要在我的Python服務器中實現Websocket握手。我的python服務器使用Twisted進行事件處理。我發現this webpage解釋了這個過程,但是當涉及到這個時,我真的很沮喪。那麼,如何實現WebSocket的握手到下面的服務器代碼:(擡起頭,我從服務器取出來我所有的項目特定代碼,使其更易於閱讀)如何在此服務器中實現WebSocket握手?

import os 
from twisted.internet.protocol import Protocol, Factory 
from twisted.internet import reactor 


class IphoneChat(Protocol): 

    def connectionMade(self): 
     #self.transport.write("""connected""") 
     #self.factory.clients.append(self) 
     print "A new client has connected" 

    def connectionLost(self, reason): 
     for c in self.factory.clients: 
      if c == self: 
       self.factory.client.remove(self) 


     print "client disconnected" 

    def dataReceived(self, data): 
     #print "Message Received: ", data 


    def message(self, message): 
     self.transport.write(message + '\n') 


factory = Factory() 
factory.protocol = IphoneChat 
factory.clients = [] 


port = 3000 
print "Server started: " 
print port 


reactor.listenTCP(port, factory) 

reactor.run() 

回答

1

首先,請注意您發現的頁面是針對尚未實際上屬於Twisted的開發中功能的文檔。您將無法使用您在該頁面上閱讀的任何內容,而無需採取您可能不想採取的特殊額外步驟。

接下來,看看http://autobahn.ws/python/,它提供了一個用於編寫WebSockets客戶端的Twisted友好的Python庫。