python学习笔记之socket(第七天)
2018-06-18 02:33:18来源:未知 阅读 ()
参考文档:
1、金角大王博客:http://www.cnblogs.com/alex3714/articles/5227251.html
2、银角大王博客:http://www.cnblogs.com/wupeiqi/articles/5040823.html
一、socket模块:
socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用【打开】【读写】【关闭】模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)
socket和file的区别:
file模块是针对某个指定文件进行【打开】【读写】【关闭】
socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】
1、具体功能介绍 :sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
参数一:地址簇
socket.AF_INET IPv4(默认)
socket.AF_INET6 IPv6
socket.AF_UNIX 只能够用于单一的Unix系统进程间通信
参数二:类型
socket.SOCK_STREAM 流式socket , for TCP (默认)
socket.SOCK_DGRAM 数据报式socket , for UDP
socket.SOCK_RAW 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
socket.SOCK_RDM 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
socket.SOCK_SEQPACKET 可靠的连续数据包服务
参数三:协议
0 (默认)与特定的地址家族相关的协议,如果是 0 ,则系统就会根据地址格式和套接类别,自动选择一个合适的协议
sk.bind(address)
s.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。
sk.listen(backlog)
开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。
backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
这个值不能无限大,因为要在内核中维护连接队列
sk.setblocking(bool)
是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。
sk.accept()
接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
接收TCP 客户的连接(阻塞式)等待连接的到来
sk.connect(address)
连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
sk.connect_ex(address)
同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061
sk.close()
关闭套接字
sk.recv(bufsize[,flag])
接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。
sk.recvfrom(bufsize[.flag])
与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。
sk.send(string[,flag])
将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。
sk.sendall(string[,flag])
将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。
内部通过递归调用send,将所有内容发送出去。
sk.sendto(string[,flag],address)
将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。
sk.settimeout(timeout)
设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
sk.getpeername()
返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
sk.getsockname()
返回套接字自己的地址。通常是一个元组(ipaddr,port)
sk.fileno()
套接字的文件描述符
举例说明:
1、socket之tcp:
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys def handle_request(client,address): buf = client.recv(1024) print(buf,address) client.sendall(("your input is %s" % buf).encode('utf-8')) def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(ip_port) sock.listen(5) while True: print('server is running...') connection, address = sock.accept() handle_request(connection,address) connection.close() if __name__ == '__main__': port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) main()
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) while True: sk = socket.socket() sk.connect(ip_port) inp = input('please input the info : ').strip() sk.sendall(('%s' % inp ).encode('utf-8')) #sk.sendall('nihao'.encode('utf-8')) if inp == 'exit': break server_reply = sk.recv(1024) print(server_reply) sk.close()
2、socket之udp:
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys def enc(strr): aa = strr.encode('utf-8') return aa if __name__ == '__main__': port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(ip_port) while True: print('server is running...') dat, address = sock.recvfrom(1024) data = dat.decode('utf-8') send_str = '' print(data,address) if data == 'exit': break if data == 'exit': break elif len(data) == '0': send_str = enc('0 ni mei...') elif data.find('nihao') >= 0 : send_str = enc('hello,baby,nihao') elif data.find('sb') >= 0 : send_str = enc('sb,to you') else: send_str = enc('input exit to exit') sock.sendto(send_str,address) sock.close()
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: inp = input('请输入:').strip() if inp == 'exit': break inpp = inp.encode('utf-8') sk.sendto(inpp,ip_port) data,address = sk.recvfrom(1024) print(data.decode('utf-8'),address) sk.close()
3、socket之类ssh执行命令:
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys,subprocess,time def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(ip_port) sock.listen(5) print('server is running...') while True: connection, address = sock.accept() while True: buf = connection.recv(1024) if not buf: break print("recv cmd:",str(buf,'utf-8')) cmd = str(buf,'utf-8').strip() cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) cmd_result = cmd_call.stdout.read() if len(cmd_result) == 0: cmd_result = b"cmd execution has no output..." ack_msg = "CMD_RESULT_SIZE|%s" % len(cmd_result) print(ack_msg) connection.send(bytes(ack_msg,'utf8')) ack_re = connection.recv(50) print(ack_re) connection.send(cmd_result) connection.close() if __name__ == '__main__': port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) main()
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) sk = socket.socket() sk.connect(ip_port) while True: inp = input('cmd : ').strip() if len(inp) == 0: continue if inp == 'q': break sk.send(bytes(inp,'utf8')) server_ack_msg = sk.recv(100) cmd_res_msg = server_ack_msg.decode().split("|") print(cmd_res_msg) if cmd_res_msg[0] == "CMD_RESULT_SIZE": cmd_res_size = int(cmd_res_msg[1]) ack_re = sk.send(b'CMD_RESULT') res = '' recv_size = 0 while recv_size < cmd_res_size: server_reply = sk.recv(500) recv_size += len(server_reply) res += str(server_reply,'utf8') else: print(res) print('==========recv done=========') sk.close()
二、socketserver
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
- First, you must create a request handler class by subclassing the
BaseRequestHandler
class and overriding itshandle()
method; this method will process incoming requests. - Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
- Then call the
handle_request()
orserve_forever()
method of the server object to process one or many requests. - Finally, call
server_close()
to close the socket.
BaseRequestHandler
class ,并且还要重写父类里handle()方法;This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.
Changed in version 3.3: Added service_actions call to the serve_forever method.
New in version 3.3.
shutdown() #停掉
Tell the serve_forever() loop to stop and wait until it does.
server_close()#关闭
Clean up the server. May be overridden.
server_address#IP地址
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.
socket #
The socket object on which the server will listen for incoming requests.
The server classes support the following class variables:
socket_type #协议类型
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.
There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.
handle_error(request, client_address) #处理错误
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard output and continue handling further requests.
handle_timeout() #
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.
server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.
server_bind() #内部调用
Called by the server’s constructor to bind the socket to the desired address. May be overridden.
verify_request(request, client_address) #判断一个请求是否合法
#!/usr/bin/python # -*- coding: utf-8 -*- import socketserver,os,sys class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): print("new conn:",self.client_address) while True: data = self.request.recv(1024).strip() if not data: break print([self.client_address],data) self.request.sendall(data.upper()) if __name__ == '__main__': port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) server = socketserver.ThreadingTCPServer(ip_port, MyTCPHandler) #多线程实现并发 #server = socketserver.ForkingTCPServer(ip_port, MyTCPHandler) #多进程实现并发 #server = socketserver.TCPServer(ip_port, MyTCPHandler) #单进程的阻塞模式 server.serve_forever()
连接客户端代码跟原来一样
#!/usr/bin/python # -*- coding: utf-8 -*- import socket,os,sys port = int(sys.argv[1]) ip_port = ('127.0.0.1',port) sk = socket.socket() sk.connect(ip_port) while True: inp = input('cmd : ').strip() if len(inp) == 0: continue if inp == 'q': break sk.send(bytes(inp,'utf8')) data = sk.recv(1024) print("server reply:",str(data,'utf8')) sk.close()
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash