Python - 模拟Web Socket 请求
Max.Bai
2017-04
需要用到socketio-client, logging
1. 安装SockeIO-Client
pip install socketio-client-2
2. 创建连接发送数据
代码语言:javascript复制from socketIO_client import SocketIO
hosts = 'http://websocke.server.com'
port = 3000
# 收到message消息处理过程
def on_message(*args):
# print "recv:", args
# print "geted:", type(args[0])
if type(args[0]) is types.DictType:
rp = args[0]
print "recv:", rp
sk = SocketIO(hosts,port=port)
sk = SocketIO(hosts,port=port,params={'token': 'ksdjfkjdf'}) #create connection with params
# add lisenter for message response
sk.on('message', on_message)
data = {
"sn": 0,
"ver": 2}
# send data to message
sk.emit('message', data, on_message)
sk.sendf(data, on_message) # default send data to message
#send data to login
sk.emit('login', data, on_message)
sk.wait_for_callbacks(seconds=1)
3. 调试
导入logging 显示调试信息
代码语言:javascript复制import logging
logging.getLogger('requests').setLevel(logging.WARNING)
logging.basicConfig(level=logging.DEBUG)
4. 调试用简单websocket服务器
nodejs 实现,需要安装nodejs
代码保存为demoserverjs格式, 启动node demoserver.js
代码语言:javascript复制var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(client){
console.log('connected');
//when get data on message
client.on('message', function(obj){
console.log("get message and return to client...");
io.emit('message', {'a':'messagetest'});
console.log("login backed...");
});
// when get data on login
client.on('login', function(obj){
console.log("get login data and return to client...");
io.emit('login', {'a':'logintest'});
console.log("login backed...");
});
client.on('event', function(data){});
client.on('disconnect', function(){
console.log('client disconnected');
});
});
console.log("server started on port 3000");
server.listen(3000);