0

I am trying to use websocket over the web, with a python server and a javascript client. For python, I am using an Autobahn (http://autobahn.ws/python/) to create a websoket server. When I use a python client (still with autobahn), all work fine. But when I try to use a webpage client, nothing works.

Python (server) code :

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
                                       WebSocketServerFactory

import asyncio
import json

def fastsquare(x):
   return x * x


def slowsquare(x):
   asyncio.sleep(2)
   return x * x

class SlowSquareServerProtocol(WebSocketServerProtocol):
   @asyncio.coroutine
   def onOpen(self):
      print("WebSocket connection open.")

   @asyncio.coroutine
   def onMessage(self, payload, isBinary):
      if not isBinary:
         obj_tmp = json.loads(payload.decode('utf8'))
         obj = json.loads(obj_tmp)
         print (obj)
         try:
            if obj[2] == "little" :
               res = slowsquare(obj[3]["valeur"])
            else :
               res = fastsquare(obj[3]["valeur"])
         except Exception as e:
            self.sendClose(1000, str(e))
         else:
            obj = json.dumps(res).encode('utf8')
            print (str(obj))
            self.sendMessage(json.dumps(res).encode('utf8'))



if __name__ == '__main__':

   import asyncio

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = SlowSquareServerProtocol

   loop = asyncio.get_event_loop()
   coro = loop.create_server(factory, 'localhost', 9000)
   server = loop.run_until_complete(coro)

   try:
      loop.run_forever()
   except KeyboardInterrupt:
      pass
   finally:
      server.close()
      loop.close()

And this is my javascript code :

<script>
function carre(){
    ws = new WebSocket("ws://192.168.0.15:9000");

    ws.onopen = function(){
        console.log("Connection is open..."); 
        // Web Socket is connected, send data using send()
        val = document.getElementById("val").value;
        var_json = '[2, "2262626262", "big", {"valeur" : ' + val + '}]';
        ws.send(var_json);
        console.log("json envoyé : " + var_json);
    };

    ws.onmessage = function (evt){ 
        var received_msg = evt.data;
        document.getElementById('carre').value = received_msg;
        console.log("JSon reçu : " + received_msg);
    };

    ws.onclose = function(){ 
        // websocket is closed.
        console.log("Connection is closed..."); 
    };
}
</script>


<p><input type="text" id="val" value="6"/><input type="button" OnClick="carre();" value="mettre au carre !"/></p>
<p>resultat du carre : <input type="text" id="carre" /></p>
Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
Army
  • 11
  • 1
  • 3
  • Please provide console messages from browser of what it says. As it is not enough information of your debugging efforts in order to help you out. In first glance, looks like you binding socket to `localhost` but really should use just port without specifying any hostname on server side. – moka Mar 12 '14 at 11:05
  • Hi, i d'ont have any error, i just have "connection is closed..." from my ws.onclose. – Army Mar 12 '14 at 13:01
  • onclose event provides object with details as first argument in callback, what that object contains? – moka Mar 12 '14 at 14:13
  • You may try looking at my demo in https://www.youtube.com/watch?v=BgpPm9N338s with source reference @ github – Yotam Oct 24 '16 at 14:07

1 Answers1

-1

Replace

obj_tmp = json.loads(payload.decode('utf8'))
obj = json.loads(obj_tmp)

with

obj = json.loads(payload)
oberstet
  • 21,353
  • 10
  • 64
  • 97
  • hello, I made this because the first json.loads give me a string and i can't recover data (ex : obj[3]["valeur"]). With a second json.load my string become a json. – Army Mar 12 '14 at 12:58
  • This answer does not fixes a problem, but just points to unrelated to issue area in code. – moka Mar 12 '14 at 14:13
  • If this actually fixes the problem, then my appologies, and will remove - once 2 hours past (SO limitations..) – moka Mar 12 '14 at 16:27
  • Yes, honestly, I tested it. Works for me. Probably the OP could test it with the change applied and see if it works for him/her. – oberstet Mar 12 '14 at 18:54
  • Hello, i tried to modify but it still doesn't work :/. – Army Mar 13 '14 at 09:05
  • Try this: https://gist.github.com/oberstet/9526275 and https://gist.github.com/oberstet/9526288 – oberstet Mar 13 '14 at 11:00