我有一个Flask服务器,当前显示一个JSON文件。我希望同一台服务器通过套接字接收数据流并将其保存到JSON。
在堆栈溢出答案的帮助下,我已经草拟了基础知识,但是,当从客户端发送数据时,将抛出404 message
并且未运行代码来处理数据(在示例打印call decoding
中) 。
服务器
from flask import Flask, json, Response
import os
import socket
import threading
app = Flask(__name__)
server_address = ('', 5001)
@app.route('/')
def index():
filename = os.path.join(app.static_folder, 'data.json')
with open(filename) as data:
data = json.load(data)
return Response(json.dumps(data), mimetype='application/json')
def launch_socket_server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(server_address)
sock.listen(1)
print('Listening...')
while True:
#Wait for connection
connection, address = sock.accept()
print('Connected', address)
try:
#Receive data
while True:
data = connection.recv(16)
print(data)
if data:
print('call decoding')
finally:
#Clean up connection
connection.close()
if __name__ == "__main__":
t = threading.Thread(target=launch_socket_server)
t.daemon = True
t.start()
app.run(debug=True, host='0.0.0.0', port=5000, use_reloader=False)
客户
import socket
server_address = ('', 5001)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
data = 'Ciao Daniela'
s.sendall(data.encode('utf-8'))
s.close()
服务器控制台错误
127.0.0.1 - - [17/Sep/2019 13:39:35] code 400, message Bad HTTP/0.9 request type ('Ciao')
127.0.0.1 - - [17/Sep/2019 13:39:35] "Ciao Daniela" HTTPStatus.BAD_REQUEST -
答案 0 :(得分:0)
您是否在Windows的公司防火墙后面?在浏览器中使用正确的端口尝试使用127.0.0.1而不是0.0.0.0。
通过客户端发送对server_address = ('127.0.0.1', 5000)
来说对我有用。使用server_address = ('', 5000)
我收到消息
WinError 10049:请求的地址在其上下文中无效
您的缩进也是错误的。套接字卡在while循环中。
while True:
#Wait for connection
connection, address = sock.accept()
print('Connected', address)
# >>> STUCK HERE <<
try:
#Receive data
while True:
data = connection.recv(16)
print(data)
if data:
print('call decoding')
finally:
#Clean up connection
connection.close()
尝试:
while True:
#Wait for connection
connection, address = sock.accept()
print('Connected', address)
try:
#Receive data
while True:
data = connection.recv(16)
print(data)
if data:
print('call decoding')
finally:
#Clean up connection
connection.close()