赞
踩
Unix Domain Socket通常称为 【unix域套接口】 或 【本地套接口】,它用于位于同一台机器(操作系统)的进程间通信。它已经被纳入POSIX Operating Systems标准。
它支持以下三种方式数据传输:
(1) 可靠的字节流传输(SOCK_STREAM, 对应TCP);
(2)有序、可靠的数据包传输(SOCK_SEQPACKET);
(3)无序、不可靠的数据包传输(SOCK_DGRAM,对应UDP)。
Unix Domain Socket 的通信基于操作系统内核的,使用文件系统作为地址命名空间(address name space)。
示例分为两部分,server端, client端
import socket
import sys
import os
serverAddr = 'xunixSocket_ex'
def serverSocket():
#create sockert
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if sock < 0:
print >> sys.stderr, 'socket error'
# bind to a file
if os.path.exists(serverAddr):
os.unlink(serverAddr)
if sock.bind(serverAddr):
print >> sys.stderr, 'socket.bind error'
#listen
if sock.listen(5):
print >> sys.stderr, 'socket.listen error'
while True:
print >> sys.stderr, 'waiting for connecting'
#waiting for client connecting
conn, clientAddr = sock.accept()
try:
# receive data
# send data to client
while True:
data = conn.recv(100)
if data:
print >> sys.stderr, 'received "%s"' %data
conn.sendall(data)
else:
break
finally:
#close the connection
conn.close()
os.unlink(serverAddr)
if __name__ == "__main__":
serverSocket()
import socket
import sys
import os
serverAddr = 'xunixSocket_ex'
def clientSocket():
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if sock < 0:
print >> sys.stderr, 'socket error'
try:
sock.connect(serverAddr)
except socket.error, msg:
print >> sys.stderr, "exception"
print >> sys.stderr, msg
sys.exit(1)
message = 'this is the message'
sock.sendall(message)
amountRecv = 0
amountSnd = len(message)
while amountRecv < amountSnd:
data = sock.recv(100)
amountRecv += len(data)
print >> sys.stderr, 'received "%s"' %data
sock.close()
if __name__ == "__main__":
clientSocket()
注:
这篇博文只是做个备忘录,后面会用详细介绍unix域套接口(使用C语言写代码示例)。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。