我正在尝试使用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轮询。我该怎么修?
提前谢谢你,伊凡。
您可能想查看gevent socketio的最新版本及其文档http://gevent-socketio.readthedocs.org/
约翰·安德森、塞巴斯蒂安·贝尔和我在2012年PyCon短跑比赛中进行了重大改革。
您还可以查看pyramid_sockjs。它与Pyramid很好地集成,并使用sockjs来实现socket.io的相同角色,可以说更容易理解。