pythonのselectモード試行

20489 ワード

#!/usr/bin/env python
# coding: utf-8
#server_select.py in python2.7
import select
import socket
import Queue
from time import sleep
# Create a TCP/IP
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(False)

# Bind the socket to the port localhost    
server_address = ('localhost', 8090)
print ('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 ('waiting for the next event')
    #   select   ,  input_list       server     
    #     socket send, recv  ,         
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

    # Handle inputs
    #               ,           select    
    for s in readable:
        #                ,              ,            
        #          
        if s is server:
            # A "readable" socket is ready to accept a connection
            connection, client_address = s.accept()
            print ('connection from', client_address)
            # this is connection not server
            connection.setblocking(0)
            #                 ,           select    
            inputs.append(connection)

            # Give the connection a queue for data we want to send
            #                  ,            
            message_queues[connection] = Queue.Queue()
        else:
            #        ,     
            #                       ,             (input_list),           
            #               
            data = s.recv(1024)
            #       
            if data != '':
                # A readable client socket has data
                print ('received "%s" from %s' % (data, s.getpeername()))
                #              socket         
                message_queues[s].put(data)
                # Add output channel for response
                #          socket  output    ,  select  
                if s not in outputs:
                    outputs.append(s)
            else:
                #         ,         input     
                # Interpret empty result as closed connection
                print ('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
                #     socket          
                del message_queues[s]

    # Handle outputs
    #            ,            ,              ,         
    #             
    for s in writable:
        try:
            #           ,              
            message_queue = message_queues.get(s)
            send_data = ''
            if message_queue is not None:
                send_data = message_queue.get_nowait()
            else:
                #         
                print "has closed "
        except Queue.Empty:
            #         
            print "%s" % str(s.getpeername())
            outputs.remove(s)
        else:
            # print "sending %s to %s " % (send_data, s.getpeername)
            # print "send something"
            if message_queue is not None:
                s.send(send_data)
            else:
                print "has closed "
            # del message_queues[s]
            # writable.remove(s)
            # print "Client %s disconnected" % (client_address)

    # # Handle "exceptional conditions"
    #        
    for s in exceptional:
        print ('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]

    sleep(1)

クライアント
# coding: utf-8
import socket


messages = ['This is the message ', 'It will be sent ', 'in parts ', ]

server_address = ('14.116.214.241', 8090)

# Create aTCP/IP socket two

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 ('connecting to %s port %s' % server_address)
#       
for s in socks:
    s.connect(server_address)
char_str = raw_input("input:")
#for index, message in enumerate(messages):
while char_str!="":
    # Send messages on both sockets
    for s in socks:
        print ('%s: sending "%s"' % (s.getsockname(), char_str + str(1)))
        s.send(bytes(char_str + str(1)).decode('utf-8'))
    char_str=raw_input()
    # Read responses on both sockets

for s in socks:
    data = s.recv(1024)
    print ('%s: received "%s"' % (s.getsockname(), data))
    if data != "":
        print ('closingsocket', s.getsockname())
        s.close()


参照先:https://www.cnblogs.com/huchong/p/8613308.html