使用epoll实现一个udp server && client
udp server
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
import select
import Queue
#创建socket对象
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#设置IP地址复用
#serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#ip地址和端口号
server_address = ("127.0.0.1", 50000)
#绑定IP地址
serversocket.bind(server_address)
print "服务器启动成功,监听IP:" , server_address
#服务端设置非阻塞
#serversocket.setblocking(False)
#超时时间
timeout = 10
#创建epoll事件对象,后续要监控的事件添加到其中
epoll = select.epoll()
#注册服务器监听fd到等待读事件集合
print "serversocket.fileno():%s" % serversocket.fileno()
epoll.register(serversocket.fileno(), select.EPOLLIN)
#文件句柄到所对应对象的字典,格式为{句柄:对象}
fd_to_socket = {serversocket.fileno():serversocket,}
print "select.EPOLLIN:%s" % select.EPOLLIN
print "select.EPOLLOUT:%s" % select.EPOLLOUT
print "select.EPOLLHUP:%s" % select.EPOLLHUP
while True:
#轮询注册的事件集合,返回值为[(文件句柄,对应的事件),(...),....]
events = epoll.poll(timeout)
if not events:
print "epoll超时无活动连接,重新轮询......"
continue
print "有" , len(events), "个新事件,开始处理......"
for fd, event in events:
socket = fd_to_socket[fd]
print "fd:%s, socket:%s, event:%s" % (fd, socket, event)
#可读事件
if event & select.EPOLLIN:
#接收数据
#data = socket.recv(1024)
data, addr = socket.recvfrom(1024)
if data:
print "收到数据:" , data
#修改读取到消息的连接到等待写事件集合(即对应客户端收到消息后,再将其fd修改并加入写事件集合)
#epoll.modify(fd, select.EPOLLOUT)
socket.sendto(data, addr)
else:
print 'client close'
#在epoll中注销客户端的文件句柄
epoll.unregister(fd)
#关闭客户端的文件句柄
fd_to_socket[fd].close()
#在字典中删除与已关闭客户端相关的信息
del fd_to_socket[fd]
#epoll.modify(fd, select.EPOLLHUP)
#关闭事件
elif event & select.EPOLLHUP:
print 'client close'
#在epoll中注销客户端的文件句柄
epoll.unregister(fd)
#关闭客户端的文件句柄
fd_to_socket[fd].close()
#在字典中删除与已关闭客户端相关的信息
del fd_to_socket[fd]
#在epoll中注销服务端文件句柄
epoll.unregister(serversocket.fileno())
#关闭epoll
epoll.close()
#关闭服务器socket
serversocket.close()
udp client
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
#创建客户端socket对象
clientsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#服务端IP地址和端口号元组
server_address = ('127.0.0.1',50000)
#客户端连接指定的IP地址和端口号
#clientsocket.connect(server_address)
while True:
#输入数据
data = raw_input('please input:')
#客户端发送数据
print "send to ..."
clientsocket.sendto(data, ('127.0.0.1',50000))
#客户端接收数据
print "receive from ..."
server_data = clientsocket.recv(1024)
print '客户端收到的数据:%s' % server_data
muahao@aliyun.com