2013-07-10 53 views
0

我正在Python中構建一個遊戲服務器。功能非常明確。服務器將偵聽端口6000,遠程客戶端將發送請求。然後服務器將建立到客戶端端口7000的連接。此後,客戶端將繼續向服務器的端口6000發送'請求'(基本上,字符串如"UP#", "DOWN#", "SHOOT#"等)。在Python中接收'請求字符串'

這是問題所在。我做了一個監聽端口6000的'服務器'。這意味着我不能將客戶端綁定到同一端口。有沒有一種方法可以在服務器中獲取傳入請求的數據字符串?到目前爲止,我只有這個。

我在這裏做錯了什麼?有關此問題的任何解決方法?總之,我可以從服務器代碼中的客戶端讀取傳入的請求字符串嗎?

在此先感謝。

def receive_data(self): 
    errorOccured = False 
    connection = None 
    try: 
     listener = socket.socket() # Create a socket object. 
     host = socket.gethostname() 
     port = 6000    # The port that the server keeps listening to. 
     listener.bind(('', port)) 
     # Start listening 
     listener.listen(5) 
     statement = ("I:P0:7,6;8,1;0,4;3,8;3,2;1,6:5,4;9,3;8,7;2,6;1,4;2,7;6,1;6,3:2,1;8,3;5,8;9,8;7,2;0,3;9,4;4,8;7,1;6,8#\n","S:P0;0,0;0#","G:P0;0,0;0;0;100;0;0:4,3,0;5,4,0;3,8,0;2,7,0;6,1,0;5,8,0;1,4,0;1,6,0#",      "C:0,5:51224:824#","G:P0;0,0;0;0;100;0;0:4,3,0;5,4,0;3,8,0;2,7,0;6,1,0;5,8,0;1,4,0;1,6,0#","G:P0;0,1;2;0;100;0;0:4,3,0;5,4,0;3,8,0;2,7,0;6,1,0;5,8,0;1,4,0;1,6,0#") 
     # This is just game specific test data 
     while True: 
      c, sockadd = listener.accept() # Establish connection with client. 
      print 'incoming connection, established with ', sockadd 

      i = 0 # Just a counter. 
      while i<len(statement): 
       try: 
        self.write_data(statement[i], sockadd[0]) 
        time.sleep(1) # The game sends updates every second to the clients 
        i = i + 1 
        #print listener.recv(1024) -- this line doesn't work. gives an error 
       except: 
        print "Error binding client" 
      c.close() # Close the connection 
     return 
    except: 
     print "Error Occurred" 
+0

更新:我發現我可以使用SocketServer來實現'RequestHandler'。我認爲這可能會有所幫助。 – damith219

+0

我建議看看http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/爲一個相當不錯的套接字服務器/客戶端實現 –

+0

@願-hart感謝您的鏈接。 – damith219

回答

0

我要回答這個問題,因爲我得到了一些幫助並找出了答案。

我能做的最基本的事情就是使用c這個客戶端連接。在這裏,而不是評論行data=listener.recv(1024)我應該使用data= c.recv(1024)。現在它可以工作。

另一種方法是將SocketServers與StreamingRequestHandler結合使用。雖然這是使用典型服務器的理想選擇,但如果涉及很多對象,則可能會降低靈活性。