import socket import platform import websocket import ssl from PyQt4.QtCore import QString from constants import * printPackets = False # Enable for debugging packets sent and received class AOtcpSocket(object): def __init__(self): self.sock = socket.socket() self.isWS = False def connect(self, ip, port): try: self.sock.connect((ip, port)) except: return False self.sock.settimeout(0.1) return True def recv(self): tempdata = "" gotIt = False while not gotIt: try: contents = self.sock.recv(16384) except (socket.timeout, socket.error) as err: error = err.args[0] if error == "timed out" or error == 10035 or err.errno == 11: return -2, [] else: # connection lost return -1, [] if not contents.endswith("%"): tempdata += contents continue else: gotIt = True if tempdata: contents = tempdata + contents tempdata = "" totals = contents.split('%') del totals[-1] for i in range(len(totals)): totals[i] = totals[i].split("#") del totals[i][-1] if printPackets: try: print "[packet] <-", totals[0] except: print "(unable to print)" return 0, totals def send(self, data): if printPackets: try: print "[packet] ->", data except: print "(unable to print)" # Qt pls if isinstance(data, QString): #return self.sock.send(unicode(data).encode('utf-8')) return self.sock.send(str(data.toUtf8())) else: return self.sock.send(data.encode('utf-8')) def close(self): self.sock.close() class AOwebSocket(object): def __init__(self): self.sock = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.isWS = True self.isSecure = False self.header = { "User-Agent": "AO2XP %s" % GAME_VERSION } def connect(self, ip, port, secure_port): try: if secure_port: try: print "[debug]", "Trying secure websocket..." self.sock.connect("wss://%s:%s" % (ip, secure_port), header=self.header) self.isSecure = True except: print "[debug]", "Connecting to secure websocket failed. Trying websocket..." self.sock.connect("ws://%s:%s" % (ip, port), header=self.header) else: print "[debug]", "Trying websocket..." self.sock.connect("ws://%s:%s" % (ip, port), header=self.header) except: return False self.sock.settimeout(0.1) return True def recv(self): try: contents = self.sock.recv() except websocket.WebSocketTimeoutException: return -2, [] except websocket.WebSocketConnectionClosedException: return -1, [] except Exception as e: return -3, e totals = contents.split('%') del totals[-1] for i in range(len(totals)): totals[i] = totals[i].split("#") del totals[i][-1] if printPackets: try: print "[packet] <-", totals[0] except: print "(unable to print)" return 0, totals def send(self, data): if printPackets: try: print "[packet] ->", data except: print "(unable to print)" return self.sock.send(unicode(data)) def close(self): self.sock.close()