Created
May 15, 2019 09:02
-
-
Save Nanguage/ae5a04fa7368320dfc058eff5ef2fd42 to your computer and use it in GitHub Desktop.
A simple chat room.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
A simple chat room. | |
https://codeburst.io/building-your-first-chat-application-using-flask-in-7-minutes-f98de4adfa5d | |
$ pip install flask flask-socketio | |
$ python chatroom.py | |
Servies run on http://127.0.0.1:5000 | |
""" | |
from flask import Flask | |
from flask_socketio import SocketIO | |
app = Flask("chatapp") | |
app.config['SECRET_KEY'] = "testapp" | |
socketio = SocketIO(app) | |
session_html = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>Flask_Chat_App</title> | |
</head> | |
<body> | |
<h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3> | |
<div class="message_holder"></div> | |
<form action="" method="POST"> | |
<input type="text" class="username" placeholder="User Name"/> | |
<input type="text" class="message" placeholder="Messages"/> | |
<input type="submit"/> | |
</form> | |
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script> | |
<script type="text/javascript"> | |
var socket = io.connect('http://' + document.domain + ':' + location.port); | |
socket.on( 'connect', function() { | |
socket.emit( 'my event', { | |
data: 'User Connected' | |
} ) | |
var form = $( 'form' ).on( 'submit', function( e ) { | |
e.preventDefault() | |
let user_name = $( 'input.username' ).val() | |
let user_input = $( 'input.message' ).val() | |
socket.emit( 'my event', { | |
user_name : user_name, | |
message : user_input | |
} ) | |
$( 'input.message' ).val( '' ).focus() | |
} ) | |
} ) | |
socket.on( 'my response', function( msg ) { | |
console.log( msg ) | |
if( typeof msg.user_name !== 'undefined' ) { | |
$( 'h3' ).remove() | |
$( 'div.message_holder' ).append( '<div><b style="color: #000">'+msg.user_name+'</b> '+msg.message+'</div>' ) | |
} | |
}) | |
</script> | |
</body> | |
</html> | |
""" | |
@app.route("/") | |
def sessions(): | |
return session_html | |
def message_received(method=['GET', 'POST']): | |
print("message was received!") | |
@socketio.on('my event') | |
def handle_my_custom_event(json, method=['GET', 'POST']): | |
print('received my event:' + str(json)) | |
socketio.emit('my response', json, callback=message_received) | |
if __name__ == "__main__": | |
socketio.run(app, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment