Problem with popup a dialog using an external TCP signal #4059
-
QuestionHi everyone, I’m a beginner in NiceGUI and web development. import asyncio
import json
from nicegui import app, ui
dialog = ui.dialog()
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
try:
while True:
data = await reader.read(1024)
if not data:
break
command_data = json.loads(data.decode())
print(f"[INFO] Received data: {command_data}")
command = command_data.get("command")
if command == "show_dialog":
text = command_data.get("content")
response = await show_dialog(text)
writer.write(json.dumps({"response": response}).encode())
await writer.drain()
else:
writer.write(json.dumps({"error": "Unknown command"}).encode())
await writer.drain()
except Exception as e:
print(f"[ERROR] {e}")
finally:
writer.close()
await writer.wait_closed()
async def start_tcp_server():
server = await asyncio.start_server(handle_client, '127.0.0.1', 65432)
async with server:
print("[INFO] TCP Server started on 127.0.0.1:65432")
await server.serve_forever()
async def show_dialog(text: str) -> str:
print(f"[INFO] Showing dialog with text: {text}")
dialog_label.text = text
dialog.open()
response = await dialog
return response
with dialog:
dialog_label = ui.label()
with ui.row():
ui.button('YES', on_click=lambda: dialog.submit('yes'))
ui.button('NO', on_click=lambda: dialog.submit('no'))
app.on_startup(start_tcp_server)
@ui.page('/')
async def main_page():
ui.label("TCP Socket Integrated with NiceGUI").classes("text-2xl")
ui.run() When I run the program and send a message using another program, I can see these in the terminal : [INFO] TCP Server started on 127.0.0.1:65432 But the dialog not pop up [SOLVES] I move dialog into main @ui.page('/')
async def main_page():
dialog = ui.dialog().mark('yes_no_dialog')
with dialog:
with ui.card():
dialog_label = ui.label()
with ui.row():
ui.button('YES', on_click=lambda: (dialog.submit('Yes')))
ui.button('NO', on_click=lambda: (dialog.submit('No')))
ui.label("TCP Socket Integrated with NiceGUI").classes("text-2xl") and using muticasting, it works if command == "show_dialog":
text = command_data.get("content")
result = ""
for client in app.clients('/'):
with client.content:
for element in ElementFilter(kind=ui.dialog, marker='yes_no_dialog'):
result = await element
writer.write(json.dumps({"response": result}).encode())
await writer.drain() |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hello NineKo, |
Beta Was this translation helpful? Give feedback.
Exactly. Moving the creation of
ui.dialog
into themain_page
function should help. And to open all dialogs, once a "show_dialog" command is received, you can use multicasting to work in the UI context of each connected client.