python开发之路SocketServer

 

SocketServer与客户端进行连接的示意图:

 只要客户端连接进来,我们就为客户端创建1个线程或进程,创建完成之后,客户端直接和创建的线程直接进行通信(即3和4步),因此这样的话可以通过这个模块传输大的文件。

 

 

1.基于线程版本的SocketServer示例

server.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import SocketServer

class MyServer(SocketServer.BaseRequestHandler):
    #重写handle方法
    def handle(self):
        # print self.request,self.client_address,self.server
        conn = self.request
        conn.sendall('welcome to call 10086,plz input 1,0 connect man servervice.')
        Flag = True
        while Flag:
            data = conn.recv(1024)
            if data == 'exit':
                Flag = False
            elif data == '0':
                conn.sendall('you have being getting man service....')
            else:
                conn.sendall('plz input again.')


if __name__ == '__main__':
    #创建SocketServer线程对象
    server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyServer)
    #执行server对象的serve_forever方法        
    server.serve_forever()

  

client.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket


ip_port = ('127.0.0.1',8009)
sk = socket.socket()
sk.connect(ip_port)
sk.settimeout(5)

while True:
    data = sk.recv(1024)
    print 'receive:',data
    inp = raw_input('please input:')
    sk.sendall(inp)
    if inp == 'exit':
        break

sk.close()

 

 

 

2.基于进程版本的SocketServer的示例(将上述服务器端中的ThreadingTCPServer换成ForkingTCPServer即可

server.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import SocketServer

class MyServer(SocketServer.BaseRequestHandler):
    #重写handle方法
    def handle(self):
        # print self.request,self.client_address,self.server
        conn = self.request
        conn.sendall('welcome to call 10086,plz input 1,0 connect man servervice.')
        Flag = True
        while Flag:
            data = conn.recv(1024)
            if data == 'exit':
                Flag = False
            elif data == '0':
                conn.sendall('you have being getting man service....')
            else:
                conn.sendall('plz input again.')


if __name__ == '__main__':
    #创建SocketServer线程对象
    server = SocketServer.ForkingTCPServer(('127.0.0.1',8009),MyServer)
    #执行server对象的serve_forever方法        
    server.serve_forever()

  

client.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket


ip_port = ('127.0.0.1',8009)
sk = socket.socket()
sk.connect(ip_port)
sk.settimeout(5)

while True:
    data = sk.recv(1024)
    print 'receive:',data
    inp = raw_input('please input:')
    sk.sendall(inp)
    if inp == 'exit':
        break

sk.close()

  

posted @ 2016-01-06 19:59  杰希  阅读(188)  评论(0编辑  收藏  举报