2013-04-01 163 views
0

爲什麼這個代碼返回我需要什麼:連接到服務器通過RCON

test2.py

import socket 

if __name__ == "__main__": 
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    sock.connect(("192.168.0.101", 28960)) 
    sock.send(b"\xFF\xFF\xFF\xFFrcon xxxxxxxxx status") 
    print (sock.recv(65565)) 
    sock.close() 

所需的輸出:

b'\xff\xff\xff\xffprint\nmap:mp_rust\nnum score ping guid name lastmsg address qport rate\n 

--- ----- ---- -------------------------------- --------------- ------- --------------------- ----- -----\n\n\x00' 

但是這個代碼總是返回:

b'\xff\xff\xff\xffdisconnect\x00' 

我的代碼

test.py

import socket 
from models import RconConnection 

if __name__ == "__main__": 
    connection = RconConnection("192.168.0.101", 28960) 
    connection.connect() 
    connection.auth("xxxxxxxx") 
    connection.send("status") 
    print(connection.response(128)) 

models.py

import socket 

class RconConnection(object): 
    def __init__(self, ip, port): 
     self.ip = ip 
     self.port = port 
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 

    def connect(self): 
     self.socket.connect(("%s" % (self.ip), self.port)) 
     return 1 

    def auth(self, password): 
     string = "\xFF\xFF\xFF\xFFrcon_password %s" % (password) 
     self.socket.send(bytearray(string, "utf-8")) 
     return 1 

    def send(self, command): 
     string = "\xFF\xFF\xFF\xFFrcon %s" % (command) 
     self.socket.send(bytearray(string, "utf-8")) 
     return 1 

    def response(self, size): 
     string = self.socket.recv(size) 
     return string 

Test2.py和(test.py + models.py)不會在同一時間運行。 test2.py和models.py中的OO實現之間的區別在哪裏?

回答

1

看起來連接建立後,兩個套接字都試圖發送數據。

... 
sock.connect(("192.168.0.101", 28960)) 
sock.send(b"\xFF\xFF\xFF\xFFrcon xxxxxxxxx status") # here 
... 

而且

... 
connection.connect() 
connection.auth("xxxxxxxx") # here 
connection.send("status") # and here! 
... 

做一個/二者的接收/發送數據時,另一種是反其道而行之,就像我已經做了以下(所以沒有更改的客戶端套接字對Rcon電話)...

import socket 

if __name__ == "__main__": 
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    sock.connect(("192.168.0.101", 28960)) 
    auth = sock.recv() # recieve "xxxxxxxx" (auth) 
    status = sock.recv() # recieve "status" 
    sock.send(b"\xFF\xFF\xFF\xFFrcon xxxxxxxxx status") 
    sock.close() 
    print "Auth:", auth 
    print "Status:", status 
+0

不,我認爲你不瞭解我的問題的條件 –