服务器端:
#-*- 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()
时间: 2024-11-08 20:37:57