python-Unix套接字

 1 #!/usr/bin/python
 2  #coding=utf-8
 3 #server
 4 import socket
 5 import sys
 6 import os
 7  
 8 server_address = './test'
 9  
10 #首先确保这个文件不能存在,只是用于本地套接字的通信,如果已经存在则不可以了
11 try:
12     os.unlink(server_address)  # 用于删除一个文件
13 except OSError:
14     if os.path.exists(server_address):
15         raise
16  
17 sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
18  
19 print >>sys.stderr,'starting up on %s'%server_address
20 sock.bind(server_address)
21 sock.listen(5)
22  
23 while True:
24     print >>sys.stderr,'waiting for a connection'
25     connection,client_address = sock.accept()
26     try:
27         print >>sys.stderr,'connection from',client_address
28         while True:
29             data = connection.recv(16)
30             print >>sys.stderr,'received "%s"'%data
31             if data:
32                 print >>sys.stderr,'sending data back to the client'
33                 connection.sendall(data)
34             else:
35                 print >>sys.stderr,'no data from',client_address
36                 break
37     finally:
38         connection.close()
 1 #!/usr/bin/python
 2  #coding=utf-8
 3 #client
 4 import socket
 5 import sys
 6  
 7 sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
 8 server_address = './test'  #本地套接字通讯是设置的不是IP而是一个文件
 9  
10 print >>sys.stderr,'connection to %s'%server_address
11  
12 try:
13     sock.connect(server_address)
14 except socket.error,msg:
15     print >>sys.stderr,msg
16     sys.exit(1)
17  
18 try:
19     message = 'This is the message.It will be repeated'
20     print >>sys.stderr,'sending "%s"'%message
21     sock.sendall(message)
22  
23     amount_received = 0
24     amount_expected = len(message)
25  
26     while amount_received < amount_expected:
27         data = sock.recv(16)
28         amount_received += len(data)
29         print >>sys.stderr,'received "%s"'%data
30 finally:
31     print >>sys.stderr,'closing socket'
32     sock.close()

 

posted @ 2017-07-17 16:29  橙云生  阅读(1189)  评论(1编辑  收藏  举报