码迷,mamicode.com
首页 > 其他好文 > 详细

IO多路复用之一

时间:2016-08-29 09:13:39      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

1.socketserver的执行流程

技术分享

import socketserver

class MyClass(socketserver.BaseRequestHandler):

    def handle(self):
        pass


obj = socketserver.ThreadingTCPServer((127.0.0.1,9999),MyClass)
obj.serve_forever()

 

IO多路复用SERVER端:

__author__ = alex
#coding:utf-8
import socket
import select

ip_port = (127.0.0.1,9999)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

inputs = [sk,]
outputs = []
while True:
    rlist,wlist,e = select.select(inputs,outputs,[],2)
    print (len(inputs),len(rlist),len(wlist),len(outputs))

    for r in rlist:
        if r == sk:
            conn,addr = r.accept()
            inputs.append(conn)
            conn.sendall(bytes(hello,utf8))
        else:
            try:
                ret = r.recv(1024)
                if not ret:
                    raise Exception("断开异常连接")
                else:
                    outputs.append(r)
            except Exception:
                inputs.remove(r)


    for w in wlist:
        w.sendall(bytes("response","utf8"))
        outputs.remove(w)

 

 

IO多路复用CLIENT端:

__author__ = alex
import socket
import select
#coding:utf-8

ip_port = (127.0.0.1,9999)
sk = socket.socket()
sk.connect(ip_port)
data = sk.recv(1024)
print (str(data,utf8))
while True:
    inp = input(">>>>>>>>")
    sk.sendall(bytes(inp,encoding=utf8))
    print (sk.recv(1024))
sk.close()

 

IO多路复用之一

标签:

原文地址:http://www.cnblogs.com/python-study/p/5816335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!