Skip to content

Instantly share code, notes, and snippets.

@AZLisme
Created May 8, 2017 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AZLisme/6d118f415ca27fc310047339ef8597ba to your computer and use it in GitHub Desktop.
Save AZLisme/6d118f415ca27fc310047339ef8597ba to your computer and use it in GitHub Desktop.
test if flask-socket.io server can detect connection lost.
# -*- encoding: utf-8 -*-
# **INSTALL REQUIREMENTS BEFORE TEST**
# pip install flask flask-socketio eventlet
# pip uninstall -y python-engineio
# pip install git+https://github.com/miguelgrinberg/python-engineio.git
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
# Change to your local ip
HOST = '192.168.1.113'
PORT = 5000
app = Flask('test_main')
socket = SocketIO(app, ping_timeout=10, ping_interval=10)
@app.route('/')
def index():
return '''
<html>
<head>
<title>Test</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/socket.io/1.7.3/socket.io.js"></script>
</head>
<body>
<h1 class="Test">
Test Started
</h1>
<ul id="message">
</ul>
<script>
var counter = 10;
function appendMessage(msg){
$('ul#message').append(`<li>${msg}</li>`);
}
function delayJob(){
if (counter > 0) {
socket.emit('msg', counter);
setTimeout(delayJob, 1000);
counter--;
} else {
socket.disconnect();
}
}
var socket = io.connect('http://%s:%d');
socket.on('connect', function(){
socket.on('disconnect', function(){
appendMessage('-> Disconnected with server.');
})
socket.on('msg', function(msg){
appendMessage('-> Recieve message: ' + msg);
})
setTimeout(delayJob, 1000);
});
</script>
</body>
</html>
''' % (HOST, PORT)
@socket.on('connect')
def connect_handler():
print('Client %s connected' % request.sid)
@socket.on('disconnect')
def disconnect_handler():
print('Client %s disconnected' % request.sid)
@socket.on('msg')
def msg_handler(msg):
emit('msg', msg)
print('Recieve client %s message: %s' % (request.sid, msg))
if __name__ == '__main__':
socket.run(app, host=HOST, port=PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment