0

为什么此代码返回我需要的内容:

测试2.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'

我的代码

测试.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))

模型.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 中的面向对象实现的区别在哪里?

4

1 回答 1

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
于 2013-04-01T14:07:16.477 回答