[Python-es] Comunicación entre Tornado y Javascript

Diego Uribe Gamez diego.uribe.gamez en gmail.com
Jue Nov 15 00:36:21 CET 2012


Encontré algo nuevo,

Con otro ejemplo logre mandar un mensaje y un texto propio
( ws.send(userInput + ' id ');) mediante un formulario, pero cuando intento
hacerlo sin el formulario (ws.send('2501');) en el mismo ejemplo no manda
nada? que sera?

------------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import tornado.web
import tornado.websocket
import tornado.ioloop

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def on_message(self, message):
        self.write_message(u"Server echoed: " + message)
        print message

application = tornado.web.Application([
    (r"/websocket", WebSocketHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html>
    <head>
        <title>WebSockets Demonstrator For LFY</title>
    </head>
    <body style="font-family: Lekton; font-size: 24pt">
        <p style="width: 800px">Powered By WebSockets. Use the form below
to chat with the server.</p>
        <div id="chatbox" style="font-size: 14pt; height: 500px; width:
800px; overflow: scroll; border: 1px solid black"></div>
        <form id="conversation" onsubmit="DispatchText()"
action="javascript:void(0);">
            <input type="text" id="message" name="message"
autocomplete="off" style="width:700px" />
            <input type="submit" id="sub" name="sub" value="Send"
style="width:90px" />
        </form>
        <script type="text/javascript">
            var ws = new WebSocket("ws://localhost:8888/websocket");
            ws.onmessage = function(evt){
                x = document.createElement("p");
                x.innerHTML = evt.data;
                document.getElementById("chatbox").appendChild(x);
            }

            ws.send('2501');

            function DispatchText(){
                var userInput = document.getElementById("message").value;
                document.getElementById("message").value = "";
                x = document.createElement("p");
                x.innerHTML = "You sent: " + userInput;
                document.getElementById("chatbox").appendChild(x);
                ws.send(userInput + ' id ');
            }
        </script>
    </body>
</html>
</html>


El 14 de noviembre de 2012 16:56, Diego Uribe Gamez <
diego.uribe.gamez en gmail.com> escribió:

> Lo coloque al final pero nada, no me imprime en la terminal el mensaje
> entrante?
>
> # python server.py
> new connection
>
>
>         $("#open").click(function(evt) {
>           evt.preventDefault();
>
>           var host = $("#host").val();
>           var port = $("#port").val();
>           var uri = $("#uri").val();
>
>           ws = new WebSocket("ws://" + host + ":" + port + uri);
>
>           ws.onmessage = function(evt) {alert("message received: " +
> evt.data)};
>
>           ws.onclose = function(evt) { alert("Connection close"); };
>
>           ws.onopen = function(evt) {
>             $("#host").css("background", "#00ff00");
>             $("#port").css("background", "#00ff00");
>             $("#uri").css("background", "#00ff00");
>           };
>
>           ws.send('hola');
>
>         });
>
>
>     def on_message(self, message):
>         print 'message received %s' % message
>
>
> El 14 de noviembre de 2012 15:55, Carlos Zuniga <carlos.zun en gmail.com>escribió:
>
> 2012/11/14 Diego Uribe Gamez <diego.uribe.gamez en gmail.com>
>> >
>> > Hola,
>> >
>> > Tengo un problema y es que no logro entender como comunicar la pagina
>> html y el servidor usando Tornado usando Javascript como intermediario, en
>> especial para traer una variable:
>> >
>> > como hago para disparar este código desde el navegador?
>> > ----------------------------------------------------------------------
>> >     def on_message(self, message):
>> >         print 'message received %s' % message
>> > ----------------------------------------------------------------------
>> >
>>
>> Por lo que veo en la documentación[0], en el navegador deberías enviar
>> un mensaje. Intenta colocar esto dentro de tu función onopen:
>>
>>     ws.send('hola');
>>
>> > y también que me imprima en terminal una variable enviada desde el
>> navegador? o en este caso el message
>>
>> Con el print que usas debería de imprimirla.
>>
>> Saludos
>>
>> [0] http://www.tornadoweb.org/documentation/websocket.html
>> --
>> A menudo unas pocas horas de "Prueba y error" podrán ahorrarte minutos
>> de leer manuales.
>> _______________________________________________
>> Python-es mailing list
>> Python-es en python.org
>> http://mail.python.org/mailman/listinfo/python-es
>> FAQ: http://python-es-faq.wikidot.com/
>>
>
>
>
> --
>  *Diego Alonso Uribe Gamez*
> ------------------------------
>
> *Desarrollador web*
>
> Twitter: @DiegoUG <http://www.twitter.com/DiegoUG>
>
> Google+: http://gplus.to/diegoug
> ------------------------------
>
>
>


-- 
 *Diego Alonso Uribe Gamez*
------------------------------

*Desarrollador web*

Twitter: @DiegoUG <http://www.twitter.com/DiegoUG>

Google+: http://gplus.to/diegoug
------------------------------
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://mail.python.org/pipermail/python-es/attachments/20121114/eb4f4809/attachment.html>


Más información sobre la lista de distribución Python-es