zoukankan      html  css  js  c++  java
  • socketserver模块

    SocketServer模块

    使用socketserver框架编写TCP服务器
    使用服务器编程,需要进行一下步骤,先建立一个请求句柄类,这个类继承自BaseRequestHandler类,建立这个类以后重写他的handle方法,然后然后实例化服务器类,把主机名,端口号和句柄类传给它,然后调用server_forever()方法来处理请求。
    服务端例子:

    #!/usr/bin/env python
    import SocketServer
    import commands
    class MyTCPHandler(SocketServer.BaseRequestHandler):
    	def handle(self):
    		while True:
    			self.data=self.request.recv(1024).strip()
    			print "going to run cmd:",self.data
    			status,result=commands.getstatusoutput(self.data)
    			self.request.sendall(result)
    if __name__=="__main__":
    	HOST='localhost'
    	PORT=9999
    	server=SocketServer.TCPServer((HOST,PORT),MyTCPHandler)
    	server.serve_forever()
    

    客户端:

    [root@wish1 413]# cat clients.py 
    #!/usr/bin/env python
    import socket
    HOST='localhost'
    PORT=9999
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((HOST,PORT))
    while True:
    	user_input=raw_input('your message: ').strip()
    	if len(user_input)==0:
    		continue
    	s.sendall(user_input)
    	print 'sending ....'
    	data=s.recv(1024)
    	print 'recevied',data
    s.close()
    

    下面的小例子实现时间服务器

    #!/usr/bin/env python
    import SocketServer
    from time import ctime
    host=''
    port=8888
    addr=(host,port)
    class MyRequest(SocketServer.StreamRequestHandler):
            def handle(self):
                    print 'connection from',self.client_address
                    self.wfile.write('[%s] %s'%(ctime(),self.rfile.readline()))
    s=SocketServer.TCPServer(addr,MyRequest)
    s.serve_forever()
    

    客户端:

    #!/usr/bin/env python
    import socket
    host='localhost'
    port=8888
    addr=(host,port)
    while True:
            s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            s.connect(addr)
            data=raw_input('>>')
            s.send('%s
    '%data)
            data=s.recv(1024)
            if not data:
                    break
            print data.strip()
            s.close()
    
  • 相关阅读:
    UICollectionView添加 HeaderView FooterView
    Swift-UIDynamic初见
    Swift归档
    通知NSNotication&通知中心NSNoticationCenter
    iOS沙盒
    lldb-320.4.152﹣Debugger commands:
    UIPickerView採摘控件的學習
    hive的优化
    zookeeper简易配置及hadoop高可用安装
    hadoop组件概念理解
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5703877.html
Copyright © 2011-2022 走看看