本文整理汇总了Python中connection.Connection.receive方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.receive方法的具体用法?Python Connection.receive怎么用?Python Connection.receive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.receive方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class Client:
def __init__(self, socket, address, port):
print 'Init Client'
ee = EventEmitter()
self._packet_sender = PacketSender(socket, address, port)
self._connection = Connection(self._packet_sender)
@self._connection.ee.on('data')
def on_data(data):
ee.emit('data', data)
def on_message(message, rinfo):
if rinfo.address is not address or rinfo.port is not port:
return
packet = Packet(message)
if packet.getIsFinish():
socket.close()
return
self._connection.receive(packet)
#socket.on('message', on_message)
def send(self, data):
self._connection.send(data)
def close(self):
self._packet_sender.send(Packet.createFinishPacket())
示例2: ClientApplication
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class ClientApplication(object):
'''
Used for testing the methods that will be available via the RTP-3251 API
'''
def __init__(self):
pass
#Client commands
def connect(self, portOfClient=12000, destIp="143.215.129.100", destPort=7000):
#Command: connect (only for projects that support bi-directional transfers)
#The FTA-client connects to the FTA-server (running at the same IP host).
self.clientConnection = Connection()
self.clientConnection.open(portOfClient, (destIp, destPort))
def getF(self, fileName):
#Command: get F (only for projects that support bi-directional transfers)
#The FTA-client downloads file F from the server (if F exists in the same directory as the fta-server executable).
fileRequestObj = ['FFFFFFFF', fileName]
self.clientConnection.send(pickle.dumps(fileRequestObj))
serialObj = None
while(serialObj == None):
serialObj = self.clientConnection.receive()
fullfilledRequest = pickle.loads(serialObj)
if (fullfilledRequest[0] == fileName+"FromServer"): #write the contents (i.e. the second item in the object array
f = open(fileName+"FromServer", "w")
# file_path = path.relpath("clientFiles/"+fileName)
f.write(fullfilledRequest[1])
f.close()
print ("Client successfully received", fileName+"FromServer")
else:
print ("Client received", fullfilledRequest[0], "but was expecting", fileName+"FromServer")
def postF(self, fileName):
#Command: post F (only for projects that support bi-directional transfers)
#The FTA-client uploads file F to the server (if F exists in the same directory as the fta-client executable).
f = open(fileName, 'r')
obj = [fileName+"AtServer", f.read()]
f.close()
self.clientConnection.send(pickle.dumps(obj))
serialObj = None
while(serialObj == None):
serialObj = self.clientConnection.receive()
serverReply = pickle.loads(serialObj)
if (serverReply[0] == fileName+"AtServer" and serverReply[1] == "confirmed"):
print (fileName + " was confirmed")
else:
print (fileName + " was not confirmed!")
def terminate(self):
#Command: disconnect (only for projects that support bi-directional transfers)
#The FTA-client terminates gracefully from the FTA-server.
self.clientConnection.terminate()
示例3: ServerApplication
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class ServerApplication():
'''
Used for testing the methods that will be available via the RTP-3251 API
'''
def __init__(self, _debug=False):
self._debug = _debug
pass
def openServer(self, portOfServer=12001):
self.serverConnection = Connection(self._debug)
self.serverConnection.open(portOfServer)
def listen(self):
while(1):
serialObj = None
while(serialObj == None):
serialObj = self.serverConnection.receive() #stuck until receives a file read or write request
requestObj = pickle.loads(serialObj)
if (requestObj[0] == "FFFFFFFF"): #client wants file
self.replyF(requestObj[1])
else: #client is posting file as ['filename', content]
f = open(requestObj[0],'w')
f.write(requestObj[1])
f.close()
fileConfirmation = [requestObj[0], 'confirmed']
self.serverConnection.send(pickle.dumps(fileConfirmation))
def replyF(self, fileName):
#Command: post F (only for projects that support bi-directional transfers)
#The FTA-client uploads file F to the server (if F exists in the same directory as the fta-client executable).
f = open(fileName, 'r')
obj = [fileName+"FromServer", f.read()]
f.close()
self.serverConnection.send(pickle.dumps(obj))
def terminate(self):
#Shuts down FTA-Server gracefully
self.serverConnection.terminate()
示例4: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class Minecraft:
"""The main class to interact with a running instance of Minecraft Pi."""
def __init__(self, connection=None, autoId=True):
if connection:
self.conn = connection
else:
self.conn = Connection()
self.camera = CmdCamera(self.conn)
self.entity = CmdEntity(self.conn)
if autoId:
try:
playerId = int(environ['MINECRAFT_PLAYER_ID'])
self.player = CmdPlayer(self.conn,playerId=playerId)
except:
self.player = CmdPlayer(self.conn)
else:
self.player = CmdPlayer(self.conn)
self.events = CmdEvents(self.conn)
self.enabledNBT = False
def spawnEntity(self, *args):
"""Spawn entity (type,x,y,z,tags) and get its id => id:int"""
return int(self.conn.sendReceive("world.spawnEntity", args))
def removeEntity(self, *args):
"""Remove entity (id)"""
self.conn.send("world.removeEntity", args)
def getBlock(self, *args):
"""Get block (x,y,z) => id:int"""
return int(self.conn.sendReceive_flat("world.getBlock", floorFlatten(args)))
def getBlockWithData(self, *args):
"""Get block with data (x,y,z) => Block"""
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return Block(*map(int, ans.split(",")[:2]))
def getBlockWithNBT(self, *args):
"""
Get block with data and nbt (x,y,z) => Block (if no NBT) or (Block,nbt)
For this to work, you first need to do setting("include_nbt_with_data",1)
"""
if not self.enabledNBT:
self.setting("include_nbt_with_data",1)
self.enabledNBT = True
try:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
except RequestError:
# retry in case we had a Fail from the setting
ans = self.conn.receive()
else:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
id,data = (map(int, ans.split(",")[:2]))
commas = 0
for i in range(0,len(ans)):
if ans[i] == ',':
commas += 1
if commas == 2:
if '{' in ans[i+1:]:
return Block(id,data,ans[i+1:])
else:
break
return Block(id,data)
"""
@TODO
"""
# must have no NBT tags in any Block instances
def getBlocks(self, *args):
"""Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int]"""
return int(self.conn.sendReceive_flat("world.getBlocks", floorFlatten(args)))
# must have no NBT tags in Block instance
def setBlock(self, *args):
"""Set block (x,y,z,id,[data])"""
self.conn.send_flat("world.setBlock", floorFlatten(args))
def setBlockWithNBT(self, *args):
"""Set block (x,y,z,id,data,nbt)"""
data = list(flatten(args))
self.conn.send_flat("world.setBlock", list(floorFlatten(data[:5]))+data[5:])
# must have no NBT tags in Block instance
def setBlocks(self, *args):
"""Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,[data])"""
self.conn.send_flat("world.setBlocks", floorFlatten(args))
def setBlocksWithNBT(self, *args):
"""Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,data,nbt)"""
data = list(flatten(args))
self.conn.send_flat("world.setBlocks", list(floorFlatten(data[:8]))+data[8:])
def getHeight(self, *args):
"""Get the height of the world (x,z) => int"""
return int(self.conn.sendReceive_flat("world.getHeight", floorFlatten(args)))
def getPlayerId(self, *args):
"""Get the id of the current player"""
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class RxPSocket:
def __init__(self, ip, port, window):
logging.debug("[DEBUG] Instantiated RxP Socket at: %s : %d with window %d", ip, port, window)
self.ip = ip
self.port = port
self.window = window
self.myBrownie = 0
self.connected = False
self.connection = None
self.closed = False
def send(self, data):
logging.debug("[DEBUG] send() called in RxPSocket")
if (self.connection == None):
raise Exception("Attempt to send data without connection.")
self.connection.send(data)
def receive(self):
logging.debug("[DEBUG] receive() called in RxPSocket")
if (self.connection == None):
raise Exception("Attempt to send data without connection.")
p = self.connection.receive()
if p.sht:
self.connection.send(Packet(self.port, self.connection.destAddress[1],
0,0,0,self.window,False,True,True,Packet.EMPTY_DATA))
self.sht_rcvd()
return
return self.connection.receive()
def __del__(self):
self.close()
def close(self):
if self.closed:
return
logging.debug("[DEBUG] close() called in RxPSocket")
if self.connection:
logging.debug("[DEBUG] socket was connected")
self.connection.send(
Packet(self.port, self.connection.destAddress[1],
0, 0, 0, self.window, False, False, True, Packet.EMPTY_DATA))
self.sht_sent()
def connect(self, ip, port):
logging.debug("[DEBUG] connect() called in RxPSocket")
self.connection = Connection(self.ip, self.port, ip, port)
self.connection.send(Packet(self.port, port, 0, 0, 0, self.window, True, False, False, Packet.EMPTY_DATA))
self.syn_sent()
def listen(self):
logging.debug("[DEBUG] listen is called in RxPSocket")
while True:
try:
self.connection = Connection.listenForConnections(self.ip, self.port)
break
except:
continue
logging.debug("[DEBUG] Listen called in RxpSocket and found connection")
self.myBrownie = random.randint(1, 2000000000)
target = time.time() + Pipe.CONNECTION_TIMEOUT
while target > time.time():
p = self.connection.receive()
if p is not None and p.syn:
# if packet contains SYN:
# send synack + brownie
self.connection.send(
Packet(self.connection.srcAddress[1], self.connection.destAddress[1], 0,
0, self.myBrownie, self.window, True, True, False, Packet.EMPTY_DATA))
break
if target > time.time():
self.syn_rcvd()
# Check if a SYN comes, if it does, call the syn_rcvd function and send synack + brownie, then go to waitforechobrownie state, and then once you receive brownie hit the established state
# packet format: (srcPort, destPort, seqNum, ackNumber, brownie, windowSize, syn, ack, sht, data)
def syn_rcvd(self):
logging.debug("[DEBUG] RxPSocket entered syn_rcvd state")
inmsg = self.connection.receive()
target = time.time() + Pipe.CONNECTION_TIMEOUT
while target > time.time():
if inmsg is not None and inmsg.brownie == self.myBrownie:
# send ack + brownie
self.connection.send(
Packet(self.connection.srcAddress[1], self.connection.destAddress[1], 0,
0, self.myBrownie, self.window, False, True, False, Packet.EMPTY_DATA))
break
if target > time.time():
self.established()
else:
self.listen()
def syn_sent(self):
logging.debug("[DEBUG] RxpSocket entered syn_sent state")
target = time.time() + Pipe.CONNECTION_TIMEOUT
while target > time.time():
inmsg = self.connection.receive()
if inmsg is not None:
break
if target < time.time():
#.........这里部分代码省略.........
示例6: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import receive [as 别名]
class Minecraft:
"""The main class to interact with a running instance of Minecraft Pi."""
def __init__(self, connection=None, autoId=True):
if connection:
self.conn = connection
else:
self.conn = Connection()
if security.AUTHENTICATION_USERNAME and security.AUTHENTICATION_PASSWORD:
self.conn.authenticate(security.AUTHENTICATION_USERNAME, security.AUTHENTICATION_PASSWORD)
self.camera = CmdCamera(self.conn)
self.entity = CmdEntity(self.conn)
self.playerId = None
if autoId:
try:
self.playerId = int(environ['MINECRAFT_PLAYER_ID'])
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
try:
self.playerId = self.getPlayerId(environ['MINECRAFT_PLAYER_NAME'])
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
if security.AUTHENTICATION_USERNAME:
try:
self.playerId = self.getPlayerId(security.AUTHENTICATION_USERNAME)
self.player = CmdPlayer(self.conn,playerId=self.playerId)
except:
self.player = CmdPlayer(self.conn)
else:
self.player = CmdPlayer(self.conn)
else:
self.player = CmdPlayer(self.conn)
self.events = CmdEvents(self.conn)
self.enabledNBT = False
def spawnEntity(self, *args):
"""Spawn entity (type,x,y,z,tags) and get its id => id:int"""
return int(self.conn.sendReceive("world.spawnEntity", args))
def removeEntity(self, *args):
"""Remove entity (id)"""
self.conn.send("world.removeEntity", args)
def getBlock(self, *args):
"""Get block (x,y,z) => id:int"""
return int(self.conn.sendReceive_flat("world.getBlock", floorFlatten(args)))
def getBlockWithData(self, *args):
"""Get block with data (x,y,z) => Block"""
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return Block(*map(int, ans.split(",")[:2]))
def getBlockWithNBT(self, *args):
"""
Get block with data and nbt (x,y,z) => Block (if no NBT) or (Block,nbt)
For this to work, you first need to do setting("include_nbt_with_data",1)
"""
if not self.enabledNBT:
self.setting("include_nbt_with_data",1)
self.enabledNBT = True
try:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
except RequestError:
# retry in case we had a Fail from the setting
ans = self.conn.receive()
else:
ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args))
return stringToBlockWithNBT(ans)
"""
@TODO
"""
def fallbackGetCuboid(self, getBlock, *args):
(x0,y0,z0,x1,y1,z1) = map(lambda x:int(math.floor(float(x))), flatten(args))
out = []
for y in range(min(y0,y1),max(y0,y1)+1):
for x in range(min(x0,x1),max(x0,x1)+1):
for z in range(min(z0,z1),max(z0,z1)+1):
out.append(getBlock(x,y,z))
return out
def fallbackGetBlocksWithData(self, *args):
return self.fallbackGetCuboid(self.getBlockWithData, args)
def fallbackGetBlocks(self, *args):
return self.fallbackGetCuboid(self.getBlock, args)
def fallbackGetBlocksWithNBT(self, *args):
return self.fallbackGetCuboid(self.getBlockWithNBT, args)
def getBlocks(self, *args):
"""
Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int]
Packed with a y-loop, x-loop, z-loop, in this order.
#.........这里部分代码省略.........