- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
现在我有一个聊天框,它使用 socket.io 和 mongoDB 与允许将文本发送到聊天框的服务器进行通信。如果需要,我可以取消 mongoDB,只要它不干扰文本的显示即可。所有这些都在我使用 ngrok 公开的本地主机端口 5000 上运行,这允许我通过域访问它。问题是,当我从域访问该应用程序时,我的服务器的所有功能都没有按预期执行(我有一个 server.js、index.html 和一个 flask-app.py), index.html 和 flask-app 工作。我将包含域以供引用。
我认为它可能需要处理 server.js 不与索引和实际返回 render_template 的 flask-app 一起运行的事实。我使用 npm start 启动服务器。
我知道我知道 index.html 是一团糟,菜鸟级别请怜悯
这是服务器:
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(4000).sockets;
// Connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
if(err){
throw err;
}
console.log('MongoDB connected...');
// Connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// Create function to send status
sendStatus = function(s){
socket.emit('status', s);
}
// Get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('output', res);
});
// Handle input events
socket.on('input', function(data){
let name = data.name;
let message = data.message;
// Insert message
chat.insert({name: name, message: message}, function(){
client.emit('output', [data]);
// Send status object
sendStatus({
message: '',
clear: true
});
});
});
// Handle clear
socket.on('clear', function(data){
// Remove all chats from collection
chat.remove({}, function(){
// Emit cleared
socket.emit('cleared');
});
});
});// end of server
});
这是 index.html(抱歉弄乱了)
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type = "text/javascript">
//==============================================
//=
</script>
<script src = "bundle.js"></script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>QuickORDR</title>
<style>
#messages{height:300px;}
</style>
<style>
{#.chat-message {#}
{# width: 100px;#}
{# word-break: break-word;#}
{# margin-bottom: 20px;#}
{#}#}
.break-all{
word-break: break-all;
}
preBot{
color:#317df7;
text-align:left;
display: block;
font-family: Helvetica;
white-space: pre;
margin: 1em 0;
}
preUser{
color:#09c64c;
display: block;
font-family: Helvetica;
white-space: pre;
margin: 1em 0;
text-align: right;
}
</style>
</head>
<body style ="background-color: #eee;">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<br>
<h1 class="text-center">
Quik Ordr
<button id="clear" class="btn btn-warning">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" name = "username" class="form-control" placeholder="Enter name..." style="display:none;" wrap="soft">
<br>
<div class="card">
<div id="messages" class="card-block", style="overflow:auto" >
</div>
</div>
<br>
<textarea id="textarea" name = "message" class="form-control" placeholder="Enter message..."></textarea>
<br />
<div class="yes" style="display:none;"><button id="yes" class="btn btn-success" display ="none">Correct</button> <button id="no" class="btn btn-danger">Incorrect</button> </div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function(){
sendStatus = function(s){
socket.emit('status', s);
}
var element = function(id){
return document.getElementById(id);
}
// Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
//var socket = io.connect('http://1372aecb.ngrok.io:4000');
socket.emit('clear'); // need to make sure that text area is clear before it can work
// Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearBtn = element('clear');
var yesBtn = element('yes');
var noBtn = element('no');
// Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
// Set status
status.textContent = s;
if(s !== statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
// Handle Output
socket.on('output', function(data){
//console.log(data);
if(data.length){
for(var x = 0;x < data.length;x++){
// Build out message div
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
if (data[x].name[0] != 'C'){
message.innerHTML = "<preBot>" + data[x].name+ data[x].message +'</preBot>';
}
else {
message.innerHTML = "<preUser>" + data[x].name + ": " + data[x].message + '</preUser>';
}
messages.appendChild(message);
messages.appendChild(document.createElement('hr'));
messages.classList.add('break-all');
console.log(message);
messages.insertBefore(message, messages.nextSibling);
}
}
});
// Get Status From Server
socket.on('status', function(data){
// get message status
setStatus((typeof data === 'object')? data.message : data);
// If status is clear, clear text
if(data.clear){
textarea.value = '';
}
});
// Handle Input
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
socket.emit('input', {
name:'Customer',
message:textarea.value
});
//takes the text from the user and sends it to the pythoncode
//returns the query code and emits it
$.ajax({
url: '/sendToBot',
data: $('textarea').serialize(),
type: 'POST',
}).done(function(data){
console.log(data);
item_summary = data['summary'];
auto_correct = data['autocorrect'];
console.log(item_summary);
console.log(auto_correct);
//emit the bot message summary
socket.emit('input',{
name: '',
message:item_summary
});
//emit the bot message autocorrect
// socket.emit('input',{
//name: 'SpellCorrect',
// message:auto_correct
//});
//dump the bot data
//if the item summary is there, activate the buttons
var bot_message = item_summary;
if(bot_message[0] == 'Q'){
$(".yes").show(1000);
}
});
event.preventDefault();
}
});//end of text click event
//use socket to clear to run the success/fail button execution
yesBtn.addEventListener('click', function(){
//ajax a trigger to add a correct tag to the messages
$.ajax({
url: '/correct',
data: $('textarea').serialize(),//just a placeholder
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
socket.emit('clear');
socket.emit('input',{
name: '',
message:'Thanks! Try Again'
});
$('.yes').hide(1000);
});
//handle the no button click
noBtn.addEventListener('click', function(){
//ajax a trigger to add an incorrect tag to the messages
$.ajax({
url: '/incorrect',
data: $('textarea').serialize(),//just a placeholder
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
//wipe the message box
socket.emit('clear');
//output the repeate code
socket.emit('input',{
name: '',
message:'Thanks! Try Again'
});
$('.yes').hide(1000);
});
// Handle Chat Clear
clearBtn.addEventListener('click', function(){
socket.emit('clear');
});
// Clear Message
socket.on('cleared', function(){
$('.yes').hide(1000);
messages.textContent = '';
});
}
})();
</script>
</body>
</html>
这是 flask 应用程序:
import os
import time
from flask import Flask,render_template, request,json,jsonify
import chatbot
import pandas as pd
#pip install pandas
#pip install nltk
#pip install
app = Flask(__name__)
messagesList = [
]
#this basically just sets the excel file to a couple of empty cells
def reset_excel():
cols = ['User TimeStamp', 'Bot TimeStamp', 'User Message', 'Bot Message', 'Status']
empty_data = [['','','','','']]
df = pd.DataFrame(empty_data, columns=cols)
df.to_csv('database.csv', encoding='utf-8', index=False)
#this makes sure that the dict is in order for the excel file
def append_in_order(dictionary_list):
the_data = [[dictionary_list[0]['user_time'], dictionary_list[2]['bot time'],
dictionary_list[3]['user'],dictionary_list[1]['bot'],dictionary_list[4]['status']]]
return the_data
#function that dumps the data to a panda then a csv
def dumpData(messagesList):
cols = ['User TimeStamp', 'Bot TimeStamp', 'User Message', 'Bot Message', 'Status']
the_data = append_in_order(messagesList)
df = pd.DataFrame(the_data, columns= cols)
with open('database.csv', 'a') as file:
df.to_csv(file, header=False, index = False)
messagesList.clear()
#initialize the time variable
ts = time.gmtime()
def printmessage(txt):
if txt == 'message list':
print(messagesList)
elif txt == 'bot fail':
print('bot failed')
print(txt)
def dummmybot(txt):
msg = chatbot.bot(txt)
return {'message': msg}
#this will lauch the html page
@app.route('/')
def chat():
return render_template('index.html')
#this will collect the input from the user
@app.route('/sendToBot', methods=['POST'])
def sendToBot():
messagesList.clear()
message = request.form['message'] #this is a string that is returned from the ajax
if message == 'reset_excel_database': #sec
reset_excel()
message_time = time.strftime("%m-%d %H:%M:%S") #grab the timestamp for the user message
messagesList.append({'user_time':message_time})
bot_message = chatbot.bot(message)
item_summary = bot_message[0]
autocorrect = bot_message[1]
send_to_chat = {'summary': item_summary, 'autocorrect':autocorrect}#pass message into bot
printmessage(bot_message[0])
printmessage(bot_message[1])
messagesList.append({'bot':send_to_chat['summary']})#append the bot message
bot_message_time = time.strftime("%m-%d %H:%M:%S")
messagesList.append({'bot time':bot_message_time}) #append the bot time
new_message = {'user':message}
messagesList.append(new_message)
return jsonify(send_to_chat) #returns the message from the bot
@app.route('/correct', methods=['POST'])
def correct():
ignore = request.form['message']#just a placeholder
correct_id = {'status':'Correct'}
messagesList.append(correct_id)
#dump the message list to a csv file using pandas
printmessage('message list')
dumpData(messagesList)
return jsonify(correct_id)
@app.route('/incorrect', methods= ['POST'])
def incorrect():
ignore = request.form['message']#just a placeholder
incorrect_id = {'status':'inc orrect'}
messagesList.append(incorrect_id)
printmessage('message list')
#dump the message list int a csv file using pandas
dumpData(messagesList)
return jsonify(incorrect_id)
if __name__=="__main__":
app.run(port = 27017)
事实证明,我需要将 Flask-socketio 与我现有的 flask 结合使用。在 html 中,我只需要有一行 var socket = io.connect()
最佳答案
您似乎有一些问题 - 这里有两个观察结果,只是查看您的客户端界面(我根本没有阅读您发布的代码)
首先,客户端 JS 资源 https://143bd63a.ngrok.io/bundle.js
返回 404,因此如果它应该服务于功能性的客户端逻辑,则永远不会加载进入浏览器。
其次,您的网络应用程序似乎在向错误的主机发出网络套接字调用。如果您使用您最喜欢的浏览器的“网络检查器”,我可以看到您的聊天消息传出请求将:
http://127.0.0.1:4000/socket.io/?EIO=3&transport=polling&t=MFIA9lc
这是不正确的,因为我的计算机不是响应的唯一服务 -
似乎应用程序实际上应该向其发出套接字请求
https://143bd63a.ngrok.io:4000
但是,这个端口似乎没有通过您的防火墙转发 - 因为即使它看起来好像您的应用程序应该在端口 4000 上监听,但是当我尝试打开套接字时,这会导致连接超时。
关于python - 如何使用将服务器链接到在暴露的本地主机上运行的 flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710001/
我对 DBT 还很陌生,正在尝试探索如何进行曝光。我已经阅读了文档 ( https://docs.getdbt.com/docs/building-a-dbt-project/exposures ),
我对 DBT 还很陌生,正在尝试探索如何进行曝光。我已经阅读了文档 ( https://docs.getdbt.com/docs/building-a-dbt-project/exposures ),
这在Python中合法吗?似乎有效... 谢谢 # with these lines you not need global variables anymore if __name__ == '__m
我正在尝试使用 tomcat Docker 镜像打包一个 war 文件。我正在尝试在图像中公开 tomcat 端口以供外部访问。 这是我的docker文件 FROM tomcat8:3.0.0 C
我一直在尝试通过 ip 连接到 docker 容器,但再次失败。当我使用“docker inspect container-id”时,我得到了这个结果。 我的虚拟盒子默认设置是: 有人可以帮我解决这个
我知道要在 docker 容器中公开端口,您可以使用 -p标志(例如 -p 1-100:1-100 )。但是有没有一种很好的方法可以将大部分可能的端口从容器暴露给主机?例如,如果我在位于 VM 中的容
我正在开发一个带有 ktor 应用程序的 Kotlin,并且我使用暴露为 ORM。我有一个引用另一个表的表。这种关系是多对一的。前任: object Users : IdTable() { ov
我正在尝试学习 polymer ,并且正在尝试制作一个基本的消息传递框架。所以我创建了一个名为 messages-framework 的小 polymer 元素,它将显示消息,并在 3 秒后删除该消息
我的问题很简单也很笼统:当调用 RESTFUL API 时,无论是我的还是外部的,将 token 暴露在前端是否是常见做法/可以?例如,在 Google map api 的文档中,他们建议使用以下代码
我们有一个包含 1000 万条记录的数据库表。我们不想使用 auto_increment,因为那样会让我们的用户知道我们有多少条记录。我们不想将其暴露给我们的竞争对手。我看到的问题是使用 UUID 或
我有以下用户表对象和实体类: object UserTable : IntIdTable() { val name = varchar("name", 256) } class User(id
对于部署在 Google kubernetes 引擎上的基于微服务的示例架构,我需要帮助来验证我的理解: 我们知道服务应该对 pod 副本集的流量进行负载平衡。 当我们创建一个 nginx 入口 Co
String caminhoFoto = getExternalFilesDir(null) + "/"+ System.currentTimeMillis() +".jpg";
我目前正在编写一个用 Parcel js 打包的 TypeScript 模块化库。应用程序将使用该库来实现特定功能。消费应用程序/网页将在其 html 中添加对我的库的引用,例如。 我想在我的库中公
mongodb 生成的 ID 在您的所有文档中都是唯一的,将其暴露给客户端的风险是什么?就像我有一个 ID 为 12345676543 的用户名 James,将它暴露给 url 是明智的吗 examp
场景:假设攻击者通过对.apk文件进行逆向工程,获取了应用中使用的Push Registration Service的SENDER ID。攻击者开发了一个类似的虚假应用程序,它具有相同/不同的包名,并
当使用 Spring Boot starter 进行 graphql 时,数据获取时抛出的所有异常都在输出控制台中显示为“执行查询时的内部服务器错误”我希望我抛出的 e.message() 的 Gra
我正在尝试使用 Docker 运行 ASP.NET Core 应用程序,并且我想将外部 wwwroot 文件夹公开给容器,以便当我从外部对其进行更改时,它们会自动对我的应用程序可用。这可能吗,使用卷?
我构建了一个 WCF 服务,它为 Web 应用程序公开自身,它接受一个对象并在客户端机器上打印数据。在我的开发机器上运行良好,该服务在我安装它的任何机器上启动并运行。我可以在客户端机器的 Web 浏览
我似乎无法弄清楚这一点。我有一个使用 scikit-learn 训练的模型,保存到一个 .pkl 文件中,我想制作一个 API 来根据它进行预测。 我已经有了进行预测的代码,它在控制台/单元测试中运行
我是一名优秀的程序员,十分优秀!