selectモジュール使用

2987 ワード

ブロック式socketとclient
接続する複数のクライアントについては、複数のスレッドでserverを処理する.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

BUFFER_SIZE = 8

def main():
    s = socket.socket()
    s.connect(("localhost", 9000))
    while True:
        i = raw_input(">>")
        s.send(i)
        print s.recv(BUFFER_SIZE)

if __name__ == '__main__':
    main()

client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

BUFFER_SIZE = 8

def main():
    s = socket.socket()
    s.connect(("localhost", 9000))
    while True:
        i = raw_input(">>")
        s.send(i)
        print s.recv(BUFFER_SIZE)

if __name__ == '__main__':
    main()

複数のクライアントの接続について、selectは1つのスレッドで処理できます.select関数署名
select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)
Wait until one or more file descriptors are ready for some kind of I/O.
The first three arguments are sequences of file descriptors to be waited for:
rlist -- wait until ready for reading
wlist -- wait until ready for writing
xlist -- wait for an ``exceptional condition''
If only one kind of condition is required, pass [] for the other lists.
A file descriptor is either a socket or file object, or a small integer
gotten from a fileno() method call on one of those.

The optional 4th argument specifies a timeout in seconds; it may be
a floating point number to specify fractions of seconds.  If it is absent
or None, the call will never time out.

The return value is a tuple of three lists corresponding to the first three
arguments; each contains the subset of the corresponding file descriptors
that are ready.

*** IMPORTANT NOTICE ***
On Windows only sockets are supported; on Unix, all file
descriptors can be used

server.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys
import time
import select

BUFFER_SIZE = 2048

def handle_conn(conn):
    r_data = conn.recv(BUFFER_SIZE)
    print("recevie : %s" % (r_data, ))
    conn.send(r_data)

def main():
    s = socket.socket(socket.AF_INET)
    s.bind(("localhost", 9000))
    s.listen(10)

    connection_list = [s, ]

    while True:
        read_list, write_list, exception_list = select.select(connection_list, [], [], 5)
        for socket_ in read_list:
            if socket_ == s:
                conn, address = socket_.accept()
                connection_list.append(conn)
            else:
                handle(conn)

if __name__ == '__main__':
    main()

client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

BUFFER_SIZE = 2048

def main():
    s = socket.socket()
    s.connect(("localhost", 9000))
    while True:
        i = raw_input(">>")
        s.send(i)
        print s.recv(BUFFER_SIZE)

if __name__ == '__main__':
    main()