为什么这段代码会返回我需要的内容:
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与test.py和models.py之间的差异在哪里?
答案 0 :(得分: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