Python select示例

import select
import socket
import sys
import queue
# Create a TCP/IP
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port
server_address = (‘localhost‘, 10000)
print (sys.stderr, ‘starting up on %s port %s‘ % server_address)
server.bind(server_address)
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
inputs = [ server ]
# Sockets to which we expect to write
outputs = [ ]
# Outgoing message queues (socket:Queue)
message_queues = {}
while inputs:

    # Wait for at least one of the sockets to be ready for processing
    print (sys.stderr, ‘waiting for the next event‘)
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

    # Handle inputs
    for s in readable:

        if s is server:
            # A "readable" socket is ready to accept a connection
            connection, client_address = s.accept()
            print (sys.stderr, ‘  connection from‘, client_address)
            connection.setblocking(0)
            inputs.append(connection)

            # Give the connection a queue for data we want to send
            message_queues[connection] = queue.Queue()

        else:
            data = s.recv(1024)
            if data:
                # A readable client socket has data
                print (sys.stderr, ‘  received "%s" from %s‘ %(data, s.getpeername()))
                message_queues[s].put(data)
                # Add output channel for response
                if s not in outputs:
                    outputs.append(s)

            else:
                # Interpret empty result as closed connection
                print (sys.stderr, ‘  closing‘, client_address)
                # Stop listening for input on the connection
                if s in outputs:
                    outputs.remove(s)
                inputs.remove(s)
                s.close()

                # Remove message queue
                del message_queues[s]

    # Handle outputs
    for s in writable:
        try:
            next_msg = message_queues[s].get_nowait()
        except queue.Empty:
            # No messages waiting so stop checking for writability.
            print (sys.stderr, ‘  ‘, s.getpeername(), ‘queue empty‘)
            outputs.remove(s)
        else:
            print (sys.stderr, ‘  sending "%s" to %s‘ %(next_msg, s.getpeername()))
            s.send(next_msg)

    # Handle "exceptional conditions"
    for s in exceptional:
        print (sys.stderr, ‘exception condition on‘, s.getpeername())
        # Stop listening for input on the connection
        inputs.remove(s)
        if s in outputs:
            outputs.remove(s)
        s.close()

        # Remove message queue
        del message_queues[s]
import socket
import sys
messages = [‘This is the message. ‘,
             ‘It will be sent ‘,
             ‘in parts.‘,
             ]

server_address= (‘localhost‘, 10000)

# Create aTCP/IP socket

socks = [socket.socket(socket.AF_INET, socket.SOCK_STREAM),
          socket.socket(socket.AF_INET,socket.SOCK_STREAM),
          ]

# Connect thesocket to the port where the server is listening

print (sys.stderr, ‘connecting to %s port %s‘ % server_address)
for s in socks:
    s.connect(server_address)
for message in messages:
    # Send messages on both sockets
    for s in socks:
        print (sys.stderr, ‘%s: sending"%s"‘ %(s.getsockname(), message))
        s.send(bytes(message,encoding=‘utf-8‘))
    # Read responses on both sockets

    for s in socks:
        data = s.recv(1024)
        print (sys.stderr, ‘%s: received"%s"‘ %(s.getsockname(), data))
        if not data:
            print (sys.stderr, ‘closingsocket‘, s.getsockname())
            s.close()
时间: 2024-10-25 05:48:37

Python select示例的相关文章

Python爬虫示例

1 #!/usr/bin/python 2 #coding:utf8 3 import re 4 import urllib 5 6 def gethtml(url): 7 page=urllib.urlopen(url) 8 html=page.read() 9 return html 10 11 def getimg(html): 12 reg=r'<img src="(http.*?\.gif)" alt' 13 imgre=re.compile(reg) 14 imgli

python入门示例程序

该实例是raspi和dsp电机运动控制板的串口uart通信: import serial class SerialHandler(): ''' raspi serial for communication ''' def __init__(self)://初始化一些默认参数,其它非初始化参数在方法中作为参数传入 self.serialdev = None//给参数赋初始值 def serial_open(self,serialdev,timeout)://用户可传入的参数,其它参数(如baudr

jQuery操作radio、checkbox、select示例

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> jQuery操作radio.checkbox.select示例 </title> <meta name="Generator" con

[Python] SQLBuilder 示例代码

用Python写一个SQLBuilder,Java版可以从 http://www.java2s.com/Code/Java/Database-SQL-JDBC/SQLBuilder.htm 看到. 附上代码: 示例代码(一): class SQLDirector: @classmethod def buildSQL(cls, builder): sql = "" sql += builder.getCommand() sql += builder.getTable() sql += b

Python select模块学习

select 是常用的异步socket 处理方法 一般用法: # iwtd,owtd,ewtd 分别为需要异步处理的读socket队列, 写socket队列(一般不用), 和错误socket队列, 返回事件的读写和错误socket队列 il,ol,el = select(iwtd,owtd,ewtd[,timeout]) for sock in il: #read the sock for sock in ol: #... for sock in el: #handle errors selec

python selenium2示例 - 日志管理

前言 在自动化测试实践过程中,必不可少的就是进行日志管理,方便调试和生产问题追踪,python提供了logging模块来进行日志的管理.下面我们就logging模块的学习和使用进行一个层层推进演示学习. Python的logging模块提供了通用的日志系统,可以方便第三方模块或应用使用.这个模块提供了不同的日志级别,并可以采用不同的方式进行日志记录,比如文件,HTTP GET/POST, SMTP, socket等等,甚至可以自定实现具体的日志记录方式. logging模块与java的log4j

python发送邮件 示例

示例1 1 import smtplib 2 from email.mime.text import MIMEText 3 from email.header import Header 4 def sedmail(): 5 sender = '[email protected]' 6 receivers = ['[email protected]'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 7 8 # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设

python select和socket配合使用基础学习,是python标准库例子

# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' import select,socket,sys,Queue #作用:等待输入或者输出通道已经准备就绪的通知 #select模块允许访问特定平台的IO监视函数,可移植接口是POSIX函数select(),unix和windows都支持这个函数,poll()只支持unix,还有一些适用于unix特定变种选项 #select()是底层操作系统实现一个直接接口,会监视套接

python selenium2示例 - email发送

前言 在进行日常的自动化测试实践中,我们总是需要将测试过程中的记录.结果等等等相关信息通过自动的手段发送给相关人员.python的smtplib.email模块为我们提供了很好的email发送等功能的实现. 纯文本邮件 在通常情况下,我们需要发送大量的纯文本类的邮件通知,或是发送概要性测试报告时,会用到此类发送方式,示例代码如下: #-*- coding:utf-8 -*- __author__ = u'苦叶子' import smtplib from email.mime.text impor