我正在使用python,flask和flask-socket.io开发聊天应用程序。
这是用于Linux nginx服务器。过去,我曾在本地计算机上尝试过flask-socket.io,但在移至服务器时,当我尝试从客户端连接至服务器时会给出net :: ERR_CONNECTION_TIMED_OUT。
server.py
import json
import os
from flask import Flask, render_template, request,session
from flask_socketio import SocketIO, send, emit
from tflearn_test import Main
from datetime import timedelta,datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey'
app.config['DEBUG'] = True
socketio = SocketIO(app)
users = {}
@app.before_request
def make_session_permanent():
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=1)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def connect():
print("connected");
@app.route('/orginate')
def orginate():
socketio.emit('server orginated', 'Something happened on the server!')
return '<h1>Sent!</h1>'
@socketio.on('username')
def receive_username(username):
users[username] = request.sid
#users.append({username : request.sid})
#print(users)
emit('userList', users, broadcast=True)
print('Username added!')
print(users)
@socketio.on('user_remove')
def user_remove(username):
if username in users:
users.pop(username)
emit('userList', users, broadcast=True)
print('Username removed! %s',username)
@socketio.on('private_message')
def private_message(payload):
message = payload['message']
send_by = payload['send_by']
sender_id=users[payload['send_by']]
if (payload['username'] == 'bot'):
chat_message=Main()
reply=chat_message.response(message)
update_file(message,send_by,payload['username'],reply)
emit('new_private_message', {"message":reply,"send_by":"bot"}, room=sender_id)
else:
recipient_session_id = users[payload['username']]
if recipient_session_id:
update_file(message,send_by,payload['username'],1)
emit('new_private_message', {"message":message,"send_by":send_by}, room=recipient_session_id)
@socketio.on('refresh_user')
def receive_message_from_user(press):
emit('userList', users, broadcast=True)
@socketio.on('username', namespace='/private')
def receive_username(username):
users[username] = request.sid
#users.append({username : request.sid})
#print(users)
print('Username added!')
@socketio.on('private_message', namespace='/private')
def private_message(payload):
recipient_session_id = users[payload['username']]
message = payload['message']
emit('new_private_message', message, room=recipient_session_id)
'''
@socketio.on('message')
def receive_message(message):
print('########: {}'.format(message))
send('This is a message from Flask.')
@socketio.on('custom event')
def receive_custom_event(message):
print('THE CUSTOM MESSAGE IS: {}'.format(message['name']))
emit('from flask', {'extension' : 'Flask-SocketIO'}, json=True)
'''
if __name__ == '__main__':
socketio.run(app,host='192.168.2.184',port=5000)
client.js $(document).ready(function(){
var socket = io.connect('http://192.168.2.184:5000');
var socket_messages = io('http://192.168.2.184:5000/messages')
$('#send').on('click', function() {
var message = $('#message').val();
socket_messages.emit('message from user', message);
});
socket_messages.on('from flask', function(msg) {
alert(msg);
});
socket.on('server orginated', function(msg) {
alert(msg);
});
var private_socket = io('http://192.168.2.184:5000/private')
$('#send_username').on('click', function() {
private_socket.emit('username', $('#username').val());
});
$('#send_private_message').on('click', function() {
var recipient = $('#send_to_username').val();
var message_to_send = $('#private_message').val();
private_socket.emit('private_message', {'username' : recipient, 'message' : message_to_send});
});
private_socket.on('new_private_message', function(msg) {
alert(msg);
});
/*
socket.on('connect', function() {
socket.send('I am now connected!');
socket.emit('custom event', {'name' : 'Anthony'});
socket.on('from flask', function(msg) {
alert(msg['extension']);
});
socket.on('message', function(msg) {
alert(msg);
});
});
*/
});