473,804 Members | 4,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Twisted: How to sendLine from outside the LineReceiver class?

Qp
Hello. I'm building a simple chat server and client interface, and I've got
everything working except for this:

While the client's basic.LineRecei ver protocol class can sendLine when a
connection is made (that is, when the class is called automatically),
whenever I try to call sendLine from another class (my ClientFactory class)
then I get the following error.

"in sendLine
return self.transport. write(line + self.delimiter)
AttributeError: 'NoneType' object has no attribute 'write'"

So, I assume the instance of the LineReceiver is not set up properly. How
do I do this?

The code I am using for the classes is as follows. The error comes when I
call chatFactory.sen dMessage():

class chatClient(basi c.LineReceiver) :

def connectionMade( self):
self.sendLine(" A new person has entered the room!")

def lineReceived(se lf, line):
app.text_output .config(state=N ORMAL) #enable text_output for insert
app.text_output .insert(END, line +"\n")
app.text_output .config(state=D ISABLED)
app.text_input. delete(0, END) #clear text_input
app.text_output .see(END) #move scrollbar to the bottom

def connectionLost( self, reason):
reactor.stop()

class chatFactory(pro tocol.ClientFac tory):
protocol = chatClient

def clientConnectio nFailed(self, connector, reason):
reactor.stop()

def clientConnectio nLost(self, connector, reason):
reactor.stop()

def sendMessage(sel f):
c = chatClient()
c.sendLine("Hey there")
<<<

Jul 18 '05 #1
2 6246
[You'll probably get more answers to Twisted questions on the Twisted
mailing-list: tw************@ twistedmatrix.c om]

On Sun, Feb 29, 2004 at 02:06:07PM -0500, Qp wrote:
Hello. I'm building a simple chat server and client interface, and I've got
everything working except for this:

While the client's basic.LineRecei ver protocol class can sendLine when a
connection is made (that is, when the class is called automatically),
whenever I try to call sendLine from another class (my ClientFactory class)
then I get the following error.

"in sendLine
return self.transport. write(line + self.delimiter)
AttributeError: 'NoneType' object has no attribute 'write'"

So, I assume the instance of the LineReceiver is not set up properly. How
do I do this?

The code I am using for the classes is as follows. The error comes when I
call chatFactory.sen dMessage():
[...] class chatFactory(pro tocol.ClientFac tory):
protocol = chatClient
[...] def sendMessage(sel f):
c = chatClient()
c.sendLine("Hey there")


I see you are using ClientFactory, so I presume you want to make a client
connection to a remote server with this protocol.

You need to connect your protocol, not just create the object out of thin
air. See:

http://twistedmatrix.com/documents/howto/clients

and also:

http://twistedmatrix.com/documents/c...tml#connectTCP

I think the easiest way to do what you need is to have the protocol's
connectionMade signal the factory:

----
class ChatClient(basi c.LineReceiver) :

def connectionMade( self):
self.sendLine(" A new person has entered the room!")
self.factory.cl ientReady(self)

def lineReceived(se lf, line):
app.text_output .config(state=N ORMAL) #enable text_output for insert
app.text_output .insert(END, line +"\n")
app.text_output .config(state=D ISABLED)
app.text_input. delete(0, END) #clear text_input
app.text_output .see(END) #move scrollbar to the bottom

def connectionLost( self, reason):
reactor.stop()

class ChatFactory(pro tocol.ClientFac tory):
protocol = ChatClient

def clientConnectio nFailed(self, connector, reason):
reactor.stop()

def clientConnectio nLost(self, connector, reason):
reactor.stop()

def startFactory(se lf):
self.messageQue ue = []
self.clientInst ance = None

def clientReady(sel f, instance):
self.clientInst ance = instance
for msg in self.messageQue ue:
self.sendMessag e(msg)

def sendMessage(sel f, msg='Hey there'):
if self.clientInst ance is not None:
self.clientInst ance.sendLine(m sg)
else:
self.messageQue ue.append(msg)
----

Note that I've added a simple message queue because it may take some time
for the connection to be established, so calls to sendMessage could fail if
called too soon. The queue avoids that problem.

A better solution might be to not write the factory at all, and use
twisted.interne t.protocol.clie ntCreator:

http://twistedmatrix.com/documents/c...ntCreator.html

----
from twisted.python import log

# Create creator and connect
clientCreator = protocol.Client Creator(reactor , ChatClient)
deferred = clientCreator.c onnectTCP(host, port)

# When connected, send a line
def connectionReady (protocol):
protocol.sendLi ne('Hey there')
deferred.addCal lback(connectio nReady)

# Log any errors that occur (such as connection failed)
deferred.addErr back(log.err)
----

-Andrew.
Jul 18 '05 #2
Qp
Thanks a ton! It all makes sense now, and it works in a much better way I
was thinking about (somehow returning a working transport object).

That helps a whole lot...

Thanks again,
QP

"Andrew Bennetts" <an************ ***@puzzling.or g> wrote in message
news:ma******** *************** *************@p ython.org...
[You'll probably get more answers to Twisted questions on the Twisted
mailing-list: tw************@ twistedmatrix.c om]

On Sun, Feb 29, 2004 at 02:06:07PM -0500, Qp wrote:
Hello. I'm building a simple chat server and client interface, and I've got everything working except for this:

While the client's basic.LineRecei ver protocol class can sendLine when a
connection is made (that is, when the class is called automatically),
whenever I try to call sendLine from another class (my ClientFactory class) then I get the following error.

"in sendLine
return self.transport. write(line + self.delimiter)
AttributeError: 'NoneType' object has no attribute 'write'"

So, I assume the instance of the LineReceiver is not set up properly. How do I do this?

The code I am using for the classes is as follows. The error comes when I call chatFactory.sen dMessage():
[...]
class chatFactory(pro tocol.ClientFac tory):
protocol = chatClient

[...]
def sendMessage(sel f):
c = chatClient()
c.sendLine("Hey there")


I see you are using ClientFactory, so I presume you want to make a client
connection to a remote server with this protocol.

You need to connect your protocol, not just create the object out of thin
air. See:

http://twistedmatrix.com/documents/howto/clients

and also:

http://twistedmatrix.com/documents/c...t.interfaces.I
ReactorTCP.html #connectTCP
I think the easiest way to do what you need is to have the protocol's
connectionMade signal the factory:

----
class ChatClient(basi c.LineReceiver) :

def connectionMade( self):
self.sendLine(" A new person has entered the room!")
self.factory.cl ientReady(self)

def lineReceived(se lf, line):
app.text_output .config(state=N ORMAL) #enable text_output for insert app.text_output .insert(END, line +"\n")
app.text_output .config(state=D ISABLED)
app.text_input. delete(0, END) #clear text_input
app.text_output .see(END) #move scrollbar to the bottom

def connectionLost( self, reason):
reactor.stop()

class ChatFactory(pro tocol.ClientFac tory):
protocol = ChatClient

def clientConnectio nFailed(self, connector, reason):
reactor.stop()

def clientConnectio nLost(self, connector, reason):
reactor.stop()

def startFactory(se lf):
self.messageQue ue = []
self.clientInst ance = None

def clientReady(sel f, instance):
self.clientInst ance = instance
for msg in self.messageQue ue:
self.sendMessag e(msg)

def sendMessage(sel f, msg='Hey there'):
if self.clientInst ance is not None:
self.clientInst ance.sendLine(m sg)
else:
self.messageQue ue.append(msg)
----

Note that I've added a simple message queue because it may take some time
for the connection to be established, so calls to sendMessage could fail if called too soon. The queue avoids that problem.

A better solution might be to not write the factory at all, and use
twisted.interne t.protocol.clie ntCreator:

http://twistedmatrix.com/documents/c...t.protocol.Cli
entCreator.html
----
from twisted.python import log

# Create creator and connect
clientCreator = protocol.Client Creator(reactor , ChatClient)
deferred = clientCreator.c onnectTCP(host, port)

# When connected, send a line
def connectionReady (protocol):
protocol.sendLi ne('Hey there')
deferred.addCal lback(connectio nReady)

# Log any errors that occur (such as connection failed)
deferred.addErr back(log.err)
----

-Andrew.


Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2386
by: Alexander Eberts | last post by:
I'm new to python so appologies to the group if this question is asked often. I'm wondering if it's possible to query an object instance to find out what arguments the instance's __init__ function was called with from *outside* the class's local namespace. For example, if I define a class Foo as follows: import sys class Foo: def __init__(self, *args): print args # no problem here
1
1136
by: Keith Rebello | last post by:
I have written a class to draw dimension lines (like you see in architectural drawings). I intend to use this class in engineering programs that have graphical output. The class has various properties like line color, arrow color, text size and color, etc. To avoid setting these properties each time I need a dimension line, I thought I would define a DimensionProperties structure and pass it to the class in one form of the...
2
1178
by: ThunderMusic | last post by:
Hi, I'm building a class library and I use some classes in my library that I would not like to expose when using the class library. I explain : I use let's say Class1, Class2 and Class3. In Class1, I have an instance of Class2 and in Class2 I have an instance of Class3. Class1 takes care of all the operations done with class2 and class2 takes care of all the operations done with class3. So, I don't want Class2 and Class3 to show when...
3
1305
by: freak | last post by:
Using PHP version: 4.3.7 I try to define my db vars outside the class! Why this will not work? class mytest{ //***************** set db settings *************************** var $HOST ; var $USERNAME; var $PASSWORD; var $DBNAME;
4
3076
by: gopal | last post by:
I have the following class template declaration //class template declaration template <class T> class A { public: T t1; A(T); }; I would like to define the class A constrcutor outside. Any help
2
1840
by: KimRaver | last post by:
How do i declare a method that returns a doublepointer to a subclass, outside the Class-definition ? That is, as of now I have Class House { ... ... Class Room {
1
3205
by: =?ISO-8859-2?Q?Miros=B3aw?= Makowiecki | last post by:
We have here class of C++ language: namespace Apt { class Name1 { public: class Name2; }; } I 'm give ebove class Name2 so a declalation of class without a definition
1
2572
SamKL
by: SamKL | last post by:
Hey, I'm no expert on PHP, and I have somewhat of an understanding of object oriented code. Anyway, getting right to the problem. I'm using PHP4, so base it off of that. Basically I have 2 classes in this code. Link_Structure, which is composed of Node classes (it's a linked list data structure), and of course the Node class. In class Node: function setActive( $i ) { $this->_data = $i; } This function is designed to set the array...
2
1868
by: Suraj Kumar | last post by:
why static member is required to redeclare outside the class ?
0
9710
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10593
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10329
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7626
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4304
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3000
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.