欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用epoll实现服务端的方法

程序员文章站 2023-08-26 20:15:54
如下所示: #!/usr/bin/python # -*- coding: utf-8 -*- import socket import select...

如下所示:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import select

send_data = "hello world!"
send_len = len(send_data)
recv_len = 1024
tcp_socket = socket.socket(socket.af_inet, socket.sock_stream)
tcp_socket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)
addr = ("0.0.0.0", 8765)
tcp_socket.bind(addr)
tcp_socket.listen(5)
tcp_socket.setblocking(false)
epoll = select.epoll()
'''(边缘触发)select.epollin | select.epollet'''
epoll.register(tcp_socket.fileno(), select.epollin)
'''因为epoll返回的触发事件对应的是套接字文件描述符,所以需要在字典中加入对应关系'''
fd_to_socket = {tcp_socket.fileno():tcp_socket}

while true :
 events = epoll.poll(-1)
 for fd, event in events:
  fd_socket = fd_to_socket[fd]
  if fd == tcp_socket.fileno():
   while true:
    try:
     new_socket, new_addr = fd_socket.accept()
    except socket.error as e:
     (errno, err_msg) = e
     print errno
     print err_msg
     if errno == 11:
      break
    print "new accpet:", new_addr
    new_socket.setblocking(false)
    new_socket.setsockopt(socket.ipproto_tcp, socket.tcp_nodelay, 1)
    epoll.register(new_socket.fileno(), select.epollin)
    fd_to_socket[new_socket.fileno()] = new_socket
  elif event&select.epollin:
   recv_datas = []
   recd = 0
   while (recd < recv_len):
    try:
     recv_data = fd_socket.recv(recv_len - recd)
     '''处理读的正常关闭'''
     if recv_data == "":
      print "close socket"
      epoll.unregister(fd)
      fd_to_socket[fd].close()
      del fd_to_socket[fd]
      break
     else:
      recv_datas.append(recv_data)
      recd = recd + len(recv_data)
    '''处理异常关闭(eagain,eintr)'''
    except socket.error as e:
     (errno, err_msg) = e
     print errno
     print err_msg
     '''因为用的水平触发,eagain我们跳出循环,等待下次触发再读就好了'''
     if errno == 11:
      break
     '''软中断打断了还要继续读'''
     elif errno == 4:
      continue
     '''其它错误我们直接关闭套接字'''
     else:
      print "close socket"
      epoll.unregister(fd)
      fd_to_socket[fd].close()
      del fd_to_socket[fd]
      break
    print repr(recv_datas)
    total_send = 0
    while total_send < send_len:
     sent = fd_socket.send(send_data[total_send:])
     if sent == 0:
      print "close socket"
      epoll.unregister(fd)
      fd_to_socket[fd].close()
      del fd_to_socket[fd]
      break
     else:
      print repr(send_data[total_send:])
      total_send = total_send + sent

其实这里的异常处理我们也可以用

except ioerror as e:
  print e.errno
  print e.strerror

以上这篇python使用epoll实现服务端的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。