Iva*_*mov 5 javascript python websocket pyramid socket.io
我正在尝试使用Pyramid和socket.io框架创建一个简单的WebSocket应用程序.服务器端代码:
from pyramid.response import Response
from pyramid_socketio.io import SocketIOContext, socketio_manage
import gevent
def includeme(config):
'''
This method is called on the application startup.
'''
config.add_route('socket.io', 'socket.io/*remaining')
class ConnectIOContext(SocketIOContext):
# self.io is the Socket.IO socket
# self.request is the request
def msg_connect(self, msg):
print "Connect message received", msg
self.msg("connected", hello="world")
# Socket.IO implementation
@view_config(route_name="socket.io")
def socketio_service(request):
print "Socket.IO request running"
print request
retval = socketio_manage(ConnectIOContext(request))
return Response(retval)
Run Code Online (Sandbox Code Playgroud)
客户代码:
<script>
var socket = null;
$(document).ready(function() {
socket = new io.Socket(null, null);
socket.on('connect', function() {
console.log("Connected");
socket.send({type: "connect", userid: 123});
});
socket.on('message', function(obj) {
console.log("Message received");
console.log("Message", JSON.stringify(obj));
if (obj.type == "some") {
console.log("do some");
}
});
socket.on('error', function(obj) {
console.log("Error", JSON.stringify(obj));
});
socket.on('disconnect', function() {
console.log("Disconnected");
});
console.log("Connecting...");
socket.connect();
});
</script>
Run Code Online (Sandbox Code Playgroud)
我需要使用此代码来使用Web套接字进行连接,但它会回退到XHR轮询.我该如何解决?
提前谢谢,伊万.
您可能希望查看最新版本的gevent-socketio及其文档,网址为http://gevent-socketio.readthedocs.org/
在John Conderson,SébastienBéal和我本人的PyCon 2012冲刺中进行了重大改革.