Python多线程Socket编程的例子

发布时间:2020-04-24编辑:脚本学堂
分享一个python多线程的例子,学习下python sockect编程的实现方法,有需要的朋友参考下。

本节内容:
python多线程之使用socket进行编程。

如果没有multitask包,请从:http://python-multitask.googlecode.com/files/multitask-0.2.0.zip下载

1,server端
 

复制代码 代码示例:
from __future__ import with_statement 
from contextlib import closing 
import socket 
import multitask 
 
def client_handler(sock): 
    with closing(sock): 
        while True: 
            data = (yield multitask.recv(sock, 1024)) 
            if not data: 
                break 
            yield multitask.send(sock, data) 
 
def echo_server(hostname, port): 
    addrinfo = socket.getaddrinfo(hostname, port, 
                                  socket.AF_INET, 
                                  socket.SOCK_STREAM) 
     
    (family, socketype, porot, canonname, sockaddr) = addrinfo[0] 
    with closing(socket.socket(family, 
                               socketype, 
                               porot)) as sock: 
        sock.setsockopt(socket.SOL_SOCKET, 
                        socket.SO_REUSEADDR, 1) 
        sock.bind(sockaddr) 
        sock.listen(5) 
        while True: 
            multitask.add(client_handler(( 
                        yield multitask.accept(sock))[0])) 
                         
if __name__ == '__main__': 
    import sys 
    hostname = '192.168.2.102' 
    port = 1111 
     
    if len(sys.argv) > 1: 
        hostname = sys.argv[1] 
     
    if len(sys.argv) > 2: 
        port = int(sys.argv[2]) 
     
    multitask.add(echo_server(hostname, port)) 
     
    try: 
        multitask.run() 
    except KeyboardInterrupt: 
        pass 

2,client端(测试python多线程socket编程)
 

复制代码 代码示例:
import socket 
 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.connect(('192.168.2.102', 1111)) 
 
sock.send('hello') 
 
data = sock.recv(1024) 
sock.close() 
print 'Received', repr(data)