我正在尝试使用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)
客户代码:
<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>
我需要此代码才能使用Web套接字进行连接,但它会回退到XHR轮询。 我该如何解决?
先谢谢你,伊万。
答案 0 :(得分:8)
您可能希望查看最新版本的gevent-socketio及其在http://gevent-socketio.readthedocs.org/
的文档由John Anderson,SébastienBéal和我本人在PyCon 2012冲刺中进行了重大改革。
答案 1 :(得分:2)
您还可以查看pyramid_sockjs。它与Pyramid很好地集成,并使用sockjs来完成socket.io的相同角色,并且可以说更容易理解。