python学习笔记之socket(第七天)
参考文档:
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()
阻塞server
#!/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()
阻塞client
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) == '':
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()
udp-server
#!/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()
udp-client
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()
执行命令server
#!/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()
执行命令client
二、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.
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.
shutdown() request. Poll(检查) for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes.
Changed in version 3.3: Added service_actions call to the serve_forever method.
This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions.
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.
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
The user-provided request handler class; an instance of this class is created for each request.
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:
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.
socket_type #协议类型
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.
Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.
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.
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.
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.
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.
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()
socketserver
连接客户端代码跟原来一样
#!/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()
socketclient
python学习笔记之socket(第七天)的更多相关文章
- python学习笔记 - 初识socket
socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. sock ...
- Python学习笔记(socket)
socket(数据传输接口) 搭建服务端 1.导入模块 import socket 2.创建socket对象 sock=socket .socket(socket_family,socket_topy ...
- Python学习笔记(七)
Python学习笔记(七): 深浅拷贝 Set-集合 函数 1. 深浅拷贝 1. 浅拷贝-多层嵌套只拷贝第一层 a = [[1,2],3,4] b = a.copy() print(b) # 结果:[ ...
- Python学习笔记基础篇——总览
Python初识与简介[开篇] Python学习笔记——基础篇[第一周]——变量与赋值.用户交互.条件判断.循环控制.数据类型.文本操作 Python学习笔记——基础篇[第二周]——解释器.字符串.列 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
- Python学习笔记进阶篇——总览
Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(Socket编程进阶&多线程.多进程) Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(异常处理) Pyth ...
- Python学习笔记九
Python学习笔记之九 为什么要有操作系统 管理硬件,提供接口. 管理调度进程,并且将多个进程对硬件的竞争变得有序. 操作系统发展史 第一代计算机:真空管和穿孔卡片 没有操作系统,所有的程序设计直接 ...
- Python学习笔记,day5
Python学习笔记,day5 一.time & datetime模块 import本质为将要导入的模块,先解释一遍 #_*_coding:utf-8_*_ __author__ = 'Ale ...
随机推荐
- java集合的复习
1:自定义的linkedList链表 https://blog.csdn.net/qq_33471403/article/details/80109620 2:用linked https://b ...
- ipdb介绍及Tensor
ipdb介绍 1.现在IPython之外使用debug功能,则需要安装ipdb(pip install ipdb),而后在需要进入调试的地方加上如下代码即可: import ipdb ipdb.set ...
- C# int[,] 和 int[][]
int[] 一维数组 int[,] 二维数组 int[] [] 交错数组 又称“数组的数组” 一维数组声明与初始化 声明: int[] a = new int[]; 声明与初始化: int arr ...
- scrapy流程
- atom编辑器安装插件报错。。
Checking for native build tools failed gyp info it worked if it ends with ok gyp info using node-gyp ...
- PHP算法学习(1) 全局唯一ID
2019年1月8日16:11:13 svn地址:svn://gitee.com/zxadmin/live_z 代码在code里面 全局唯一ID 生产 后续会添加其他方法 <?php /* ...
- vins-mono:雅可比矩阵的推导
imu残差公式 我们计算雅可比采用加扰动形式 以下是位置增量偏差对旋转qbk的雅可比推导 对应的雅可比矩阵的代码 jacobian_pose_i.block<, >(O_P, O_R) = ...
- python hashlib模块 md5加密 sha256加密 sha1加密 sha512加密 sha384加密 MD5加盐
python hashlib模块 hashlib hashlib主要提供字符加密功能,将md5和sha模块整合到了一起,支持md5,sha1, sha224, sha256, sha384, ...
- go 并发编程(3)
channel go语言提供的消息通信机制被称为channel. "不要通过共享内存来通信,而应该通过通信来共享内存". channel是go语言在语言级别提供的goroutine ...
- .gitignore文件的配置和生效
1.配置 a)确保.gitignore文件和.git文件夹在同级目录 b)配置语法 # # 此为注释 – 将被 Git 忽略 *.a # 忽略所有 .a 结尾的文件 !lib.a # 但 lib.a ...