在linux上编写socket服务端程序一般可以用select、poll、epoll三种方式,本文主要介绍使用poll和epoll编写socket服务端模块。
使用poll方式的服务器端程序代码:
import socket
import select
import Queue
server_address=('10.0.2.15',21345)
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setblocking(False)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.bind(server_address)
server.listen(5)
message_queues={}
#poll时间单位是毫秒
timeout = 1000
# Create a limit for the event
READ_ONLY = ( select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
READ_WRITE = (READ_ONLY|select.POLLOUT)
# Set up the poller
poller = select.poll()
poller.register(server,READ_ONLY)
#Map file descriptors to socket objects
#server.fileno()是获得server这个socket的文件描述符,是int类型
fd_to_socket = {server.fileno():server,}
while True:
events = poller.poll(timeout)
#fd是描述符,flag是event状态,都是int类型
for fd ,flag in events:
# Retrieve the actual socket from its file descriptor
#s为当前的socket对象