我真的不知道如何在后端使用websocket并将其集成到移动应用程序中。
卡夫卡制作人:
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka
消费者py:
from kafka import KafkaConsumer
from flask import Flask
import json
new_msg = ""
app = Flask(__name__)
@app.route('/')
def hello_world():
return new_msg
consumer = KafkaConsumer('Hello-Kafka',bootstrap_servers='localhost:9092')
for msg in consumer:
if(len(msg.value.decode("utf-8"))!=0):
new_msg = msg.value.decode("utf-8")
app.run()
kafkaConsumer(value_deserializer=lambda m: json.loads(m.decode('ascii')))
mobileapp。swift:
import UIKit
class ViewController: UIViewController {
let myNotification = Notification.Name(rawValue:"MyNotification")
override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
nc.addObserver(forName:myNotification, object:nil, queue:nil, using:catchNotification)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let nc = NotificationCenter.default
nc.post(name:myNotification,
object: nil,
userInfo:["message":"Hello there!", "date":Date()])
}
func catchNotification(notification:Notification) -> Void {
print("Catch notification")
guard let userInfo = notification.userInfo,
let message = userInfo["message"] as? String,
let date = userInfo["date"] as? Date else {
print("No userInfo found in notification")
return
}
let alert = UIAlertController(title: "Notification!",
message:"\(message) received at \(date)",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
现在,在消费了卡夫卡之后,我只能向浏览器发送一条消息。如何将其集成到移动应用程序中,以便我可以将我消费的每一条消息发送到该应用程序中?