该实例采用socket实现,与socket网络编程不一样的是socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)的第一个参数是socket.AF_UNIX
而不是 socket.AF_INET
例中两个python程序 s.py/c.py 要先运行s.py
基于fedora13/python2.6测试,成功实现!
s.py代码如下:
#!/usr/bin/env python
import socket
import os
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
if not os.path.exists(conn):
os.mknod(conn)
if os.path.exists(conn):
os.unlink(conn)
sock.bind(conn)
sock.listen(5)
while True:
connection,address = sock.accept()
data = connection.recv(1024)
if data == "hello,server":
print "the client said:%s!\n" % data
connection.send("hello,client")
connection.close()
c.py代码如下:
#!/usr/bin/env python
import socket
import time
if __name__ == '__main__':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn = '/tmp/conn'
sock.connect(conn)
time.sleep(1)
sock.send('hello,server')
print sock.recv(1024)
sock.close()
import sys, thread()ing, queueif sys.version_info.major == 3:
def execfile(filename, globals=None, locals=None):
g = globals if globals is not None else __builtins__.globals()
l = locals if locals is not None else __builtins__.locals()
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, g, l)
if __name__ == '__main__':
f1 = '/path/to/file1.py' # MainThread
f2 = '/path/to/file2.py'
# 将需要共享的变量放入全局变量字典,在f1和f2中可以直接使用q1和q2两个队列
# f1向f2发送消息:
# f1: q1.put(something)
# f2: q1.get()
# f2向f1发送消息:
# f2: q2.put(something)
# f1: q2.get()
g = {'q1': queue.Queue(), 'q2': queue.Queue()}
g.update(globals())
thread = threading.Thread(target=execfile, args=(f2, ), kwargs={'globals':g})
thread.start()
execfile(f1, globals=g)
thread.join()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)