当应用程序在 gtk.main() 中运行时,如何监听套接字? [英] How to listen socket, when app is running in gtk.main()?
问题描述
我尝试过搜索,但似乎没有任何效果.例如:
I've tried to search, but nothing seems to work. For example:
我目前正在使用 PyGTK 在 Python2.7 中编写简单的通信应用程序.我有后台进程,它正在像那样在 while 循环中监听套接字.当我从服务器收到消息时,我想显示消息.但是当我启动 gtk.main() 时,它显然又开始循环了,所以我的监听循环不起作用.我需要为每条消息显示新窗口或关闭旧窗口并显示所有未读消息的新窗口.我可以以某种方式显示窗口(或多个窗口)并且不阻塞我的监听循环吗?
I am currently writing simple communication app in Python2.7 with PyGTK. I have background process, which is listening socket in while loop like that. I want to display message, when I receive it form server. But when I start gtk.main(), it obviously starts to loop again, so my listening loop doesn't working. I need to display new window for each message or close old window and display new window with all unread messages. Can I somehow display window (or more than one window) and don't block my listening loop?
IOChannel 解决方案
while True: #listening loop
print 'Start'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((socket.gethostname(), 80))
sock.listen(2)
conn, address = sock.accept()
conn.sendall('200 OK')
fd = conn.fileno() #Make file descriptor from socket
gio_channel = glib.IOChannel(fd) #Pass it to IOChannel
if(new_message):
#display message with gtk.main()
else
#Do something else like update file
subprocess.Popen 解决方案
while True: #listening loop
print 'Start'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((socket.gethostname(), 80))
sock.listen(2)
conn, address = sock.accept()
conn.sendall('200 OK')
all_json = conn.recv(2048)
if(new_message):
# This script run pygtk app in the background
subprocess.Popen(['python', 'communication_app.py'])
else
#Do something else like update file
推荐答案
您可能想尝试使用 GLib 的 GIOChannel
(Python 文档中的 GLib.IOChannel)将套接字作为 en 事件处理源(GSource
).然后使用g_io_create_watch
(Python中的GLib.IOChannel.add_watch
)集成到GTK+主循环中.
You may want to give a try using GLib's GIOChannel
(GLib.IOChannel in the Python doc) to handle the sockets as en event source (a GSource
). Then use g_io_create_watch
(GLib.IOChannel.add_watch
in Python) to integrate in GTK+ main loop.
- https://lazka.github.io/pgi-docs/#GLib-2.0/classes/IOChannel.html#GLib.IOChannel
- https://developer.gnome.org/glib/stable/glib-IO-Channels.html
Gio
库中还有许多更高级的套接字处理内容:
You also have lots of more advanced socket handling stuff in the Gio
library:
- https://lazka.github.io/pgi-docs/#Gio-2.0
- https://developer.gnome.org/gio/stable/(参见低级网络支持"和高级网络功能"部分)
- https://lazka.github.io/pgi-docs/#Gio-2.0
- https://developer.gnome.org/gio/stable/ (see "Low-level network support" and "High-level network functionallity" sections)
这篇关于当应用程序在 gtk.main() 中运行时,如何监听套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!