使用Flask接收套接字数据

时间:2019-09-17 11:15:42

标签: python python-3.x sockets flask

我有一个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 -

1 个答案:

答案 0 :(得分:0)

  • 您是否在Windows的公司防火墙后面?在浏览器中使用正确的端口尝试使用127.0.0.1而不是0.0.0.0。

  • 通过客户端发送对server_address = ('127.0.0.1', 5000)来说对我有用。使用server_address = ('', 5000)我收到消息

  

WinError 10049:请求的地址在其上下文中无效

  • 为套接字和Web服务器使用两个不同的端口。我刚刚尝试使用5000和5001,但效果很好。

您的缩进也是错误的。套接字卡在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()