python 使用epoll异步处理多个客户端的连接

服务器端:

#-*- coding:utf8 -*-
import socket
import select
import os

address = "0.0.0.0"
port = 10001
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

def main():
     global address,port,sock
     epoll = select.epoll()
     #获取创建好的sock的文件描述符
     fd = sock.fileno()
     sock.bind((address,port))
     sock_dict = {}
     sock_dict[fd] = sock
     #对该sock进行注册
     epoll.register(fd,select.EPOLLIN)
     sock.listen(5)
     while True:
         events = epoll.poll(1)
         for fileno,event in events:
	     #获取到的文件描述符和sock的相同就说明是一个新的连接
             if fileno == fd:
                 (client,address) = sock.accept()
                 print address
                 client.setblocking(0)
		 #将新的连接进行注册,用来接收消息
                 epoll.register(client.fileno(),select.EPOLLIN)
                 sock_dict[client.fileno()] = client
            elif event & select.EPOLLIN:
                 print "fileno:",fileno
                 data = sock_dict[fileno].recv(128)
                 if data == '你好':
                     print "Data:",data.decode('UTF-8')
                     sock_dict[fileno].send("你好")
                elif len(data) == 0:
                     print "线路%d已下线"%fileno
                     epoll.unregister(fileno)
                else:
                     print "Data:",data
if __name__ == '__main__':
    main()

客户端:

#coding: UTF-8
  
import socket
import select

address = "127.0.0.1"
port = 10001
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

def main():
    global address,port,sock
    sock.connect((address,port))
    epoll = select.epoll()
    fd = sock.fileno()
    #这里的epoll注册只是用来异步接收服务端发过来的消息
    epoll.register(fd,select.EPOLLIN)
    while True:
        events = epoll.poll(1)
        for fileno,event in events:
            if fileno == fd:
                if event & select.EPOLLIN:
                    data = sock.recv(128)
                    print data
        data = raw_input(">")
        if data == 'q':
            break
        elif data == '':
            print "不能发送空消息"
            continue
        sock.send(data)
    sock.close()
main()



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值