Twisted client protocol - attaching an interface frontend

2024/10/12 15:27:47

I am following the tutorial on writing a client/server pair in Twisted located here:

http://twistedmatrix.com/documents/current/core/howto/clients.html

I have everything working for the communication of my client and server, the system uses custom prefixes to denote how far it is into the 'conversation'. It sends a json string initially to set up the session, and then sends a file line by line. It's really just an exercise more than anything else.

Client.py:

class ClientProtocol(protocol.Protocol):def connectionMade(self):json_string = json.dumps({'uid':ObjectId(),'lat':43.78,'lon':-72.5831},cls=Encoder)self.transport.write('OPN|'+json_string)self.fileObject = open('test.csv')def sendFile(self):lineData = self.fileObject.readline()if lineData != '':self.transport.write('UPD|')self.transport.write(lineData)else:self.transport.write('EOF|done')def dataReceived(self,data):if data in ['ELLO','RECVD']:self.sendFile()class ClientFactory(protocol.Factory):def buildProtocol(self,addr):return ClientProtocol()if __name__ == '__main__':point = TCP4ClientEndpoint(reactor,'localhost',5000)d = point.connect(ClientFactory())reactor.run()

Server:

    class TransferProtocol(protocol.Protocol):ran = 0def connectionLost(self,reason):print reasondef connectionMade(self):self.fileObject = open('output','w')def dataReceived(self,data):methods = {'OPN':'open','UPD':'upload','EOF':'endfile'}if data[0:3] in methods.keys():func = getattr(self,methods[data[0:3]])func(data[4:])def open(self,data):print 'OPEN %s' % dataself.transport.write('ELLO')def endfile(self,data):print 'END %s' % dataself.transport.loseConnection()def upload(self,data):self.ran+=1self.fileObject.write(data)self.transport.write('RECVD')class myProtocolFactory(protocol.Factory):protocol = TransferProtocoldef doStart(self):passdef startedConnecting(self, connectorInstance):print connectorInstancedef buildProtocol(self, address):print addressreturn self.protocol()def clientConnectionLost(self, connection, reason):print reasonprint connectiondef clientConnectionFailed(self, connection, reason):print connectionprint reasondef doStop(self):passif __name__ == '__main__':reactor.listenTCP(5000, myProtocolFactory())reactor.run()

Currently, I run the server in one terminal and the client in another. As expected, both reactors start and communicate once, the client transmits it's identity json followed by the file contents and then terminates the connection. What I can't understand is how to 'hook up' this protocol to something like the cmd interface, to make it spawn these processes on command after one ends. Because the reactor in the client runs indefinitely, it performs the network conversation once and then just loops through continuously in the reactor.

Everything I've ever build with Twisted, client or server, just responded to network calls, so I am wondering what would be the correct approach to making this a "one-shot" client protocol that would activate on input commands from cmd. Would one even use the reactor for something like this? Or Twisted at all for that matter as opposed to just manually opening sockets that follow the protocol?

EDIT

I've found the Twisted stdio library fishing around on google and SO, but I'm having trouble hooking the terminal input protocol up to the network protocol.

I have the terminal protocol inherit for LineReceiver, and the prompts show correctly. I've assigned the network factory to the terminal protocol's factory object, and then attempt to call methods of the network protocol from the prompt. The problem is, the connector object assigned to this property doesn't use any of the methods of the protocol it's supposed to create.

I've put it on GitHub for brevity's sake:

https://github.com/DeaconDesperado/swfty-share/blob/master/client.py

Answer

No There is no need for external wiring for bringing both your server and client services up together.

Twisted provides the necessary means to ensure that it can start all your services and bring them down when you shut down a twisted application. It provides the facility to do this.

Read this excellent tutorial on twisted application:

  1. http://krondo.com/?p=2345

Read the following for more details:

  1. http://twistedmatrix.com/documents/current/core/howto/basics.html
  2. http://twistedmatrix.com/documents/current/core/howto/application.html
  3. http://twistedmatrix.com/documents/current/core/howto/plugin.html
  4. http://twistedmatrix.com/documents/current/core/howto/tap.html

On SO:

  1. Twisted application without twistd
https://en.xdnf.cn/q/118186.html

Related Q&A

Get query string as function parameters on flask

Is there a way to get query string as function parameters on flask? For example, the request will be like this.http://localhost:5000/user?age=15&gender=MaleAnd hope the code similar to this.@app.…

cython.parallel cannot see the difference in speed

I tried to use cython.parallel prange. I can only see two cores 50% being used. How can I make use of all the cores. i.e. send the loops to the cores simultaneously sharing the arrays, volume and mc_vo…

Is it possible (how) to add a spot color to pdf from matplotlib?

I am creating a chart which has to use (multiple) spot colors. This color could be one that is neither accessible from RGB nor CMYK. Is there a possibility to specify a spot color for a line in matplot…

Separate keywords and @ mentions from dataset

I have a huge set of data which has several columns and about 10k rows in more than 100 csv files, for now I am concerned about only one column with message format and from them I want to extract two p…

Kivy class in .py and .kv interaction 2

Follow up from Kivy class in .py and .kv interaction , but more complex. Here is the full code of what Im writing: The data/screens/learnkanji_want.kv has how I want the code to be, but I dont fully un…

How to centre an image in pygame? [duplicate]

This question already has an answer here:How to center an image in the middle of the window in pygame?(1 answer)Closed 1 year ago.I am using python 2.7, I would like to know if there is a way to centr…

widget in sub-window update with real-time data in tkinter python

Ive tried using the after/time.sleep to update the treeview, but it is not working with the mainloop. My questions are: How can I update the treeview widget with real-time data? And is there a way th…

Changing for loop to while loop

Wondering how would the following for loop be changed to while loop. While having the same output.for i in range(0,20, 4):print(i)

How to dynamically resize label in kivy without size attribute

So, I get that you can usually just use self(=)(:)texture_size (py,kv) but all of my widgets are either based on screen(root only) or size_hint. I am doing this on purpose for a cross-platform GUI. I o…

How to parallelize this nested loop in Python that calls Abaqus

I have the nested loops below. How can i parallelize the outside loop so i can distribute the outside loop into 4 simultaneous runs and wait for all 4 runs to complete before moving on with the rest of…