赞
踩
11.2.4 UNIX域套接字
从程序员的角度来看,使用UNIX域套接字和TCP/IP套接字村长两个根本区别。首先,套接字的地址是文件系统上的一个路径,而不是一个包含服务器名和端口的元组。其次,文件系统中创建的表示套接字的节点会持久保存,即使套接字关闭也仍然存在,所以每次服务器启动时都需要将其删除。只需在设置部分做一些修改,就可以把前面的回送服务器例子更新为使用UDS。
需要基于地址簇AF_Unix创建socket。套接字的绑定和入站连接的管理与对TCP/IP套接字的做法相同。
import socket import sys import os server_address = './uds_socket' # Make sure the socket does not already exist. try: os.unlink(server_address) except OSError: if os.path.exists(server_address): raise # Create a UDS socket. sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) # Bind the socket to the address. print('starting up on {}'.format(server_address)) sock.bind(server_address) # Listen for incoming connections. sock.listen(1) while True: # Wait for a connection. print('waiting for a connection') connection,client_address = sock.accept() try: print('connection from',client_address) # Receive the data in small chunks and retransmit it. while True: data = connection.recv(16) print('received {!r}'.format(data)) if data: print('sending data back to the client') connection.sendall(data) else: print('no data from',client_address) break finally: # Clean up the connection. connection.close()
还需要修改客户设置以使用UDS。要假设套接字的相应文件系统节点存在,因为服务器要通过绑定这个地址创建套接字。UDS客户中发送和接收数据的做法与前面的TCP/IP客户是一样的。
import socket import sys # Create a UDS socket. sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) # Connect the socket to the port where the server is listening. server_address = './uds_socket' print('connecting to {}'.format(server_address)) try: sock.connect(server_address) except socket.error as msg: print(msg) sys.exit(1) try: # Send data. message = b'This is the message. It will be repeated.' print('sending {!r}'.format(message)) sock.sendall(message) amount_received = 0 amount_expected = len(message) while amount_received < amount_expected: data = sock.recv(16) amount_received += len(data) print('received {!r}'.format(data)) finally: print('closing socket') sock.close()
程序输出基本上相同,但对地址信息有适当的更新。服务器显示接收的消息和发回给客户的消息。
客户立即发送所有消息,并采用增量方式逐个部分地接收消息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。