Python async TCP server: cannot get sockets from it -


i'm trying simulate network using asychronious tcp servers , sockets. used example documentation starting point task. here's code of server class:

import asyncio import socket import node  class serverprotocol(asyncio.protocol):     def __init__(self, hostnode):         self.hostnode = hostnode      def connection_made(self, transport):         peername = transport.get_extra_info('peername')         print('connection {}'.format(peername))         self.transport = transport      def data_received(self, data):         print('data received: {!r}'.format(data))         self.hostnode.processincomingmessage(data)  class nodeserver:     def __init__(self, hostnode):         self.loop = asyncio.get_event_loop()         self.hostnode = hostnode      def startlistening(self):         self.coro = self.loop.create_server(serverprotocol(self.hostnode), '', 0, family=socket.af_inet)         server = self.loop.run_until_complete(self.coro)      def getportnumber(self):         print(self.coro.sockets)         portnumber = self.coro.sockets[0].getpeername()[1]         print(portnumber)         return portnumber 

i call create_server function params '', 0 , family=socket.af_inet because need establish ipv4 version , os must give appropriate random port listen. in code below i'm trying number of port. documentation says, create_server function returns server object, , sockets can retrieved sockets attribute. when run code, following error:

attributeerror: 'generator' object has no attribute 'sockets' 

it happens when executing self.coro.sockets

so, that's issue.

could me this, please?

many thanks.

the call create_server returns coroutine. server instance has sockets attribute returned when call run_until_complete. change definition of startlistening save return value of run_until_complete self.server , modify getportnumber definition use instead. need change getpeername getsockname port allocated.

class nodeserver:     def __init__(self, hostnode):         self.loop = asyncio.get_event_loop()         self.hostnode = hostnode      def startlistening(self):         self.coro = self.loop.create_server(serverprotocol(self.hostnode), '', 0, family=socket.af_inet)         self.server = self.loop.run_until_complete(self.coro)      def getportnumber(self):         print(self.server.sockets)         portnumber = self.server.sockets[0].getsockname()[1]         print(portnumber)         return portnumber 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -