[英]websocket : python server and client js -> didn't work
I am trying to use websocket over the web, with a python server and a javascript client . 我正在尝试通过python服务器和javascript客户端在网络上使用websocket 。 For python , I am using an
Autobahn (http://autobahn.ws/python/)
to create a websoket server . 对于python ,我正在使用
Autobahn (http://autobahn.ws/python/)
创建一个websoket服务器 。 When I use a python client (still with autobahn), all work fine. 当我使用python客户端(仍然使用高速公路)时,一切正常。 But when I try to use a webpage client, nothing works.
但是,当我尝试使用网页客户端时,没有任何效果。
Python (server) code : Python(服务器)代码:
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 : 这是我的javascript代码:
<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>
Replace 更换
obj_tmp = json.loads(payload.decode('utf8'))
obj = json.loads(obj_tmp)
with 与
obj = json.loads(payload)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.