How can I organise program, which should have non-blocking connection on Python?
My question is next: I want to write a program which should connect to the same program on the other machine, and both this program should exchange some informa开发者_如何学编程tion. I can't set up non-blocking connection. How can it be?
Take a look at the asyncore library: http://docs.python.org/library/asyncore.html
And specifically, the asynchat examples: http://docs.python.org/library/asynchat.html#asynchat.async_chat
It should do exactly what you need here.
The most simple solution to have a non-blocking socket in Python is just to use the setblocking() method on the socket. Something like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
# bind, accept or connect stuff
s.recv(100) # will not block and if no data available a "socket.error"
# exception will be raised
You may also want to take a look at settimeout()
If you want to pass Python objects, you can "serialize" them with the pickle module and send them through sockets, as described in other answers.
精彩评论