简体   繁体   English

扭曲,在收到客户请求后返回自定义消息给客户端

[英]twisted , return custom message to client after receiving request from client

I have Written a simple code of http server and http client, i am able to successfully send messages to server in form of xml from client. 我写了一个简单的http服务器和http客户端代码,我能够成功地从客户端以xml的形式向服务器发送消息。 here's my code. 这是我的代码。

client.py client.py

from StringIO import StringIO
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

from twisted.web.client import FileBodyProducer
from xml_dict import bm_xml

xml_str = bm_xml()
agent = Agent(reactor)
body = FileBodyProducer(StringIO(xml_str))

d = agent.request(
   'GET',
   'http://localhost:8080/',
    Headers({'User-Agent': ['Replication'],
            'Content-Type': ['text/x-greeting']}),
    body)

def cbResponse(response):
    print response.version
d.addCallback(cbResponse)

def cbShutdown(ignored):
   reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

server.py server.py

from twisted.web import server, resource
from twisted.internet import reactor

def parse_xml(xml_str):
  print xml_str
  response = "xml_to_client"
  return response



class Simple(resource.Resource):
     isLeaf = True
     def render_GET(self, request):
        xml_request_str = request.content.read()
        response = parse_xml(xml_request_str)
        print response

 site = server.Site(Simple())
 reactor.listenTCP(8080, site) 
 reactor.run()

what i am trying to do here is from client i am sending an xml string to server, xml is generated from bm_xml module which is another file. 我想在这里做的是从客户端我发送一个xml字符串到服务器,xml是从bm_xml模块生成的,这是另一个文件。 this xml is successfully read to server, now once once server receives the xml, i need to parse this xml and return another xml string. 这个xml成功读取到服务器,现在一旦服务器收到xml,我需要解析这个xml并返回另一个xml字符串。 i have the code to parse xml and construct another xml so that client receives this xml from server, but i do not know how to send the message to client from server. 我有解析xml的代码并构造另一个xml,以便客户端从服务器接收此xml,但我不知道如何从服务器将消息发送到客户端。 where all the changes would the required , in server or client ? 在服务器或客户端中所需的所有更改? i am assuming cbresponse is the one where changes has to be done in client , but i have no idea where the change should be done in server side. 我假设cbresponse是必须在客户端进行更改的那个,但我不知道在服务器端应该在哪里进行更改。 In server response variable is the one which i need to send to client. 在服务器response变量是我需要发送给客户端的变量。

You code appears to already do what you are asking. 您的代码似乎已经按照您的要求进行操作。 Simple.render_GET returns response . Simple.render_GET返回response response is what is sent to the client. response是发送给客户端的内容。 Perhaps you're unsure how to get the response after it has been sent to the client? 也许您不确定如何在将响应发送给客户端后获得响应? If so, the answer may be readBody ( more docs ). 如果是这样,答案可能是readBody更多文档 )。

I found what i wanted : this is my updated Code for client.py 我找到了我想要的东西:这是我更新的client.py代码

 from StringIO import StringIO

 from twisted.internet import reactor
 from twisted.internet.protocol import Protocol
 from twisted.web.client import Agent
 from twisted.web.http_headers import Headers
 from twisted.internet.defer import Deferred

 from twisted.web.client import FileBodyProducer
 from xml_dict import bm_xml

 xml_str = bm_xml()
 agent = Agent(reactor)
 body = FileBodyProducer(StringIO(xml_str))

 class BeginningPrinter(Protocol):
     def __init__(self, finished):
         self.finished = finished
         self.remaining = 1024 * 10

     def dataReceived(self, bytes):
        if self.remaining:
            reply = bytes[:self.remaining]
            print reply

    def connectionLost(self, reason):
         print 'Finished receiving body:', reason.getErrorMessage()
         self.finished.callback(None)


  d = agent.request(
   'POST',
   'http://localhost:8080/',
    Headers({'User-Agent': ['Replication'],
            'Content-Type': ['text/x-greeting']}),
    body)

  def cbRequest(response):
      finished = Deferred()
      response.deliverBody(BeginningPrinter(finished))
      return finished

  d.addCallback(cbRequest)

  def cbShutdown(ignored):
  reactor.stop()

  d.addBoth(cbShutdown)
  reactor.run()

and this is my server.py 这是我的server.py

  from twisted.web import server, resource
  from twisted.internet import reactor
  from xml_parser import parser
  from twisted.web.resource import Resource

  def parse_xml(xml_str):
       print xml_str
       xml_response = parser(xml_str)
       return xml_response

 class re_simple(Resource):
       isLeaf = True
       def render_POST(self, request):
            xml_request_str = request.content.read()
            xml_response = parse_xml(xml_request_str)
            return xml_response

 site = server.Site(re_simple())
 reactor.listenTCP(8080, site)
 print "server started"
 reactor.run()

Now i send the Request : <some Xml> to server and i get the response from server <some response> . 现在我将Request: <some Xml>发送到服务器,我从服务器<some response>获得<some response>

this is what i wanted. 这就是我想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Twisted 中的异步客户端不发送/接收请求(使用 NetStringReceiver) - Asynchronous client in Twisted not sending / receiving request (using NetStringReceiver) Twisted聊天客户端只在发送消息后直接收到消息? - Twisted chat client only receives message directly after sending a message? 扭曲的网络-响应客户端后保留请求数据 - Twisted web - Keep request data after responding to client 如何编写Webapp2请求处理程序以允许客户端在收到Channel API消息后获取数据 - How to write a Webapp2 Request Handler to Allow Client to Get Data after receiving Channel API message Autobahn twisted websocket 服务器不会向客户端发送消息,除非它收到来自客户端的消息 - Autobahn twisted websocket server does not send messages to client unless it receives a message from a client 如何在收到来自客户端的消息后在 TKINTER GUI 上显示值(使用套接字)(Python) - How to display values on TKINTER GUI after receiving a message from a client(using sockets) (Python) Pyro4客户端未收到消息 - Pyro4 client not receiving message 使用twisted.conch作为客户端使用ssh接收扩展数据 - Receiving extended data with ssh using twisted.conch as client 从扭曲的客户端向服务器发送多条消息 - Send multiple messages to server from twisted client 从扭曲的服务器向特定客户端发送数据 - sending data to particular client from twisted server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM