加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python之路,Day8 - Socket网络编程

发布时间:2020-12-17 00:06:23 所属栏目:Python 来源:网络整理
导读:本节内容 Socket介绍 Socket参数介绍 基本Socket实例 Socket实现多连接处理 通过Socket实现简单SSH 通过Socket实现文件传送 作业:开发一个支持多用户在线的FTP程序 1. Socket介绍 概念 A? network socket ?is an endpoint of a connection across a?. Today

本节内容

  1. Socket介绍
  2. Socket参数介绍
  3. 基本Socket实例
  4. Socket实现多连接处理
  5. 通过Socket实现简单SSH
  6. 通过Socket实现文件传送
  7. 作业:开发一个支持多用户在线的FTP程序

1. Socket介绍

概念

A?network socket?is an endpoint of a connection across a?. Today,most communication between computers is based on the?; therefore most network sockets are?Internet sockets. More precisely,a socket is a??(abstract reference) that a local program can pass to the networking??(API) to use the connection,for example "send this data on this socket".

For example,to send "Hello,world!" via??to port 80 of the host with address 1.2.3.4,one might get a socket,connect it to the remote host,send the string,then close the socket.

实现一个socket至少要分以下几步,(伪代码)

A?socket API?is an??(API),usually provided by the?,that allows application programs to control and use network sockets. Internet socket APIs are usually based on the??standard. In the Berkeley sockets standard,sockets are a form of??(a?file?handle),due to the??that "everything is a file",and the analogies between sockets and files: you can read,write,open,and close both.?  

A?socket address?is the combination of an??and a?,much like one end of a telephone connection is the combination of a??and a particular?. Sockets need not have an address (for example for only sending data),but if a program?binds?a socket to an address,the socket can be used to receive data sent to that address. Based on this address,internet sockets deliver incoming data packets to the appropriate application??or?.

Socket Families(地址簇)

These constants represent the address (and protocol) families,used for the first argument to?. If the??constant is not defined then this protocol is unsupported. More constants may be available depending on the system.

Socket Types

These constants represent the socket types,used for the second argument to?. More constants may be available depending on the system. (Only??and??appear to be generally useful.)

2. Socket 参数介绍

family=AF_INET,?type=SOCK_STREAM,?proto=0,?fileno=None

Create a new socket using the given address family,socket type and protocol number. The address family should be??(the default),?,?,??or?. The socket type should be?(the default),?,??or perhaps one of the other??constants. The protocol number is usually zero and may be omitted or in the case where the address family is??the protocol should be one of??or?. If?fileno?is specified,the other arguments are ignored,causing the socket with the specified file descriptor to return. Unlike?,?fileno?will return the same socket and not a duplicate. This may help close a detached socket using?.

familytypeproto

Build a pair of connected socket objects using the given address family,socket type,and protocol number. Address family,and protocol number are as for the??function above. The default family is??if defined on the platform; otherwise,the default is?.

addresstimeoutsource_address

Connect to a TCP service listening on the Internet?address?(a 2-tuple?),and return the socket object. This is a higher-level function than?: if?host?is a non-numeric hostname,it will try to resolve it for both??and?,and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.

Passing the optional?timeout?parameter will set the timeout on the socket instance before attempting to connect. If no?timeout?is supplied,the global default timeout setting returned by??is used.

If supplied,?source_address?must be a 2-tuple??for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.

host,?port,?family=0,?type=0,?flags=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()?

  套接字的文件描述符

file,?offset=0,?count=None

? ? ?发送文件 ,但目前多数情况下并无什么卵用。

3. 基本Socket实例

前面讲了这么多,到底咋么用呢?

server = socket.socket() server.bind((,9998)) server.listen() ( conn,addr = server.accept() ( data = conn.recv(1024 ( server.close()
client = client.connect((,9998 client.send(b client.close()

上面的代码的有一个问题, 就是SocketServer.py运行起来后, 接收了一次客户端的data就退出了。。。, 但实际场景中,一个连接建立起来后,可能要进行多次往返的通信。

多次的数据交互怎么实现呢?

server = socket.socket() server.bind((,addr ) data = conn.recv(1024 ( server.close()
client = client.connect((,9998 msg = input(>: len(msg) == 0: client.send( msg.encode( data = client.recv(1024 ( client.close()

实现了多次交互, 棒棒的, 但你会发现一个小问题, 就是客户端一断开,服务器端就进入了死循环,为啥呢?

看客户端断开时服务器端的输出

。 收到消息: b'' 收到消息: b'' 收到消息: b'' 收到消息: b''

知道了原因就好解决了,只需要加个判断服务器接到的数据是否为空就好了,为空就代表断了。。。

server = socket.socket() server.bind((,addr ) data = conn.recv(1024 ( ( server.close()

4.Socket实现多连接处理

上面的代码虽然实现了服务端与客户端的多次交互,但是你会发现,如果客户端断开了, 服务器端也会跟着立刻断开,因为服务器只有一个while 循环,客户端一断开,服务端收不到数据 ,就会直接break跳出循环,然后程序就退出了,这显然不是我们想要的结果 ,我们想要的是,客户端如果断开了,我们这个服务端还可以为下一个客户端服务,它不能断,她接完一个客,擦完嘴角的遗留物,就要接下来勇敢的去接待下一个客人。 在这里如何实现呢?

我们知道上面这句话负责等待并接收新连接,对于上面那个程序,其实在while break之后,只要让程序再次回到上面这句代码这,就可以让服务端继续接下一个客户啦。?

server = socket.socket() #获得socket实例

server.bind(("localhost",9998)) #绑定ip port
server.listen() #开始监听

while True: #第一层loop
print("等待客户端的连接...")
conn,只到有客户端连接进来...
print("新连接:",addr )
while True:

    data = conn.recv(1024)
    if not data:
        print("客户端断开了...")
        break #这里断开就会再次回到第一次外层的loop
    print("收到消息:",data)
    conn.send(data.upper())

server.close()

注意了, 此时服务器端依然只能同时为一个客户服务,其客户来了,得排队(连接挂起),不能玩 three some. 这时你说想,我就想玩3p,就想就想嘛,其实也可以,多交钱嘛,继续往下看,后面开启新姿势后就可以玩啦。。。

5.通过socket实现简单的ssh

光只是简单的发消息、收消息没意思,干点正事,可以做一个极简版的ssh,就是客户端连接上服务器后,让服务器执行命令,并返回结果给客户端。

server = socket.socket() <span style="color: #008000;">#<span style="color: #008000;">获得socket实例<span style="color: #008000;">

<span style="color: #008000;">server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

<span style="color: #000000;">
server.bind((<span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",9998)) <span style="color: #008000;">#<span style="color: #008000;">绑定ip port
server.listen() <span style="color: #008000;">#<span style="color: #008000;">开始监听

<span style="color: #0000ff;">while True: <span style="color: #008000;">#<span style="color: #008000;">第一层loop
<span style="color: #0000ff;">print(<span style="color: #800000;">"<span style="color: #800000;">等待客户端的连接...<span style="color: #800000;">"<span style="color: #000000;">)
conn,addr = server.accept() <span style="color: #008000;">#<span style="color: #008000;">接受并建立与客户端的连接,只到有客户端连接进来...
<span style="color: #0000ff;">print(<span style="color: #800000;">"<span style="color: #800000;">新连接:<span style="color: #800000;">"<span style="color: #000000;">,addr )
<span style="color: #0000ff;">while<span style="color: #000000;"> True:

    data </span>= conn.recv(1024<span style="color: #000000;"&gt;)
    </span><span style="color: #0000ff;"&gt;if</span> <span style="color: #0000ff;"&gt;not</span><span style="color: #000000;"&gt; data:
        </span><span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;客户端断开了...</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;)
        </span><span style="color: #0000ff;"&gt;break</span> <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;这里断开就会再次回到第一次外层的loop</span>
    <span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;收到命令:</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,data)
    res </span>= os.popen(data.decode()).read() <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;py3 里socket发送的只有bytes,os.popen又只能接受str,所以要decode一下</span>
    <span style="color: #0000ff;"&gt;print</span><span style="color: #000000;"&gt;(len(res))
    conn.send(res.encode(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;utf-8</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;))

server.close()

client =<span style="color: #000000;"> socket.socket()

client.connect((<span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",9998<span style="color: #000000;">))

<span style="color: #0000ff;">while<span style="color: #000000;"> True:
msg = input(<span style="color: #800000;">"<span style="color: #800000;">>>:<span style="color: #800000;">"<span style="color: #000000;">).strip()
<span style="color: #0000ff;">if len(msg) == 0:<span style="color: #0000ff;">continue<span style="color: #000000;">
client.send( msg.encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">"<span style="color: #000000;">) )

data </span>= client.recv(1024<span style="color: #000000;"&gt;)
</span><span style="color: #0000ff;"&gt;print</span>(data.decode()) <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;命令执行结果</span>

<span style="color: #000000;">
client.close()

very cool,这样我们就做了一个简单的ssh,但多试几条命令你就会发现,上面的程序有以下2个问题。?

  1. 不能执行top等类似的 会持续输出的命令,这是因为,服务器端在收到客户端指令后,会一次性通过os.popen执行,并得到结果后返回给客户,但top这样的命令用os.popen执行你会发现永远都不会结束,所以客户端也永远拿不到返回。(真正的ssh是通过select 异步等模块实现的,我们以后会涉及)
  2. 不能执行像cd这种没有返回的指令, 因为客户端每发送一条指令,就会通过client.recv(1024)等待接收服务器端的返回结果,但是cd命令没有结果 ,服务器端调用conn.send(data)时是不会发送数据给客户端的。 所以客户端就会一直等着,等到天荒地老,结果就卡死了。解决的办法是,在服务器端判断命令的执行返回结果的长度,如果结果为空,就自己加个结果返回给客户端,如写上"cmd exec success,has no output."
  3. 如果执行的命令返回结果的数据量比较大,会发现,结果返回不全,在客户端上再执行一条命令,结果返回的还是上一条命令的后半段的执行结果,这是为什么呢?这是因为,我们的客户写client.recv(1024), 即客户端一次最多只接收1024个字节,如果服务器端返回的数据是2000字节,那有至少9百多字节是客户端第一次接收不了的,那怎么办呢,服务器端此时不能把数据直接扔了呀,so它会暂时存在服务器的io发送缓冲区里,等客户端下次再接收数据的时候再发送给客户端。 这就是为什么客户端执行第2条命令时,却接收到了第一条命令的结果的原因。 这时有同学说了, 那我直接在客户端把client.recv(1024)改大一点不就好了么, 改成一次接收个100mb,哈哈,这是不行的,因为socket每次接收和发送都有最大数据量限制的,毕竟网络带宽也是有限的呀,不能一次发太多,发送的数据最大量的限制 就是缓冲区能缓存的数据的最大量,这个缓冲区的最大值在不同的系统上是不一样的, 我实在查不到一个具体的数字,但测试的结果是,在linux上最大一次可接收10mb左右的数据,不过官方的建议是不超过8k,也就是8192,并且数据要可以被2整除,不要问为什么 。anyway,如果一次只能接收最多不超过8192的数据 ,那服务端返回的数据超过了这个数字怎么办呢?比如让服务器端打开一个5mb的文件并返回,客户端怎么才能完整的接受到呢?那就只能循环收取啦。?

在开始解决上面问题3之前,我们要考虑,客户端要循环接收服务器端的大量数据返回直到一条命令的结果全部返回为止, 但问题是客户端知道服务器端返回的数据有多大么?答案是不知道,那既然不知道服务器的要返回多大的数据,那客户端怎么知道要循环接收多少次呢?答案是不知道,擦,那咋办? 总不能靠猜吧?呵呵。。。 当然不能,那只能让服务器在发送数据之前主动告诉客户端,要发送多少数据给客户端,然后再开始发送数据,yes,机智如我,搞起。

先简单测试接收数据量大小

server = socket.socket() <span style="color: #008000;">#<span style="color: #008000;">获得socket实例
server.setsockopt(socket.SOL_SOCKET,1<span style="color: #000000;">)

server.bind((<span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",data)
<span style="color: #008000;">#<span style="color: #008000;">res = os.popen(data.decode()).read() #py3 里socket发送的只有bytes,所以要decode一下
res = subprocess.Popen(data,shell=True,stdout=subprocess.PIPE).stdout.read() <span style="color: #008000;">#<span style="color: #008000;">跟上面那条命令的效果是一样的
<span style="color: #0000ff;">if len(res) ==<span style="color: #000000;"> 0:
res = <span style="color: #800000;">"<span style="color: #800000;">cmd exec success,has not output!<span style="color: #800000;">"<span style="color: #000000;">
conn.send(str(len(res)).endcode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">")) <span style="color: #008000;">#<span style="color: #008000;">发送数据之前,先告诉客户端要发多少数据给它
conn.sendall(res.encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">")) <span style="color: #008000;">#<span style="color: #008000;">发送端也有最大数据量限制,所以这里用sendall,相当于重复循环调用conn.send,直至数据发送完毕
<span style="color: #000000;">
server.close()

client =<span style="color: #000000;"> socket.socket()

client.connect((<span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",9998<span style="color: #000000;">))

<span style="color: #0000ff;">while<span style="color: #000000;"> True:
msg = input(<span style="color: #800000;">"<span style="color: #800000;">>>:<span style="color: #800000;">"<span style="color: #000000;">).strip()
<span style="color: #0000ff;">if len(msg) == 0:<span style="color: #0000ff;">continue<span style="color: #000000;">
client.send( msg.encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">"<span style="color: #000000;">) )

res_return_size  </span>= client.recv(1024) <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;接收这条命令执行结果的大小</span>
<span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;getting cmd result,</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res_return_size)
total_rece_size </span>=<span style="color: #000000;"&gt; int(res_return_size)
</span><span style="color: #0000ff;"&gt;print</span><span style="color: #000000;"&gt;(total_rece_size)

</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;print(data.decode()) #命令执行结果</span>

<span style="color: #000000;">
client.close()

>:cat /var/log/system.log getting cmd result,b'3472816Sep 9 09:06:37 Jies-MacBook-Air kernel[0]: hibernate image path: /var/vm/sleepimagenSep 9 09:06:37 Jies-MacBook-Air kernel[0]: efi pagecount 65nSep 9 09:06:37 Jies-MacBook-Air kernel[0]: hibernate_page_list_setall(preflight 1) startnSep 9 09:06:37 Jies-MacBook-Air kernel[0]: hibernate_page_list_setall time: 211 msnSep 9 09:06:37 Jies-MacBook-Air kernel[0]: pages 1211271,wire 225934,act 399265,inact 4,cleaned 0 spec 97,zf 3925,throt 0,compr 218191,xpmapped 40000nSep 9 09:06:37 Jies-MacBook-Air kernel[0]: could discard act 94063 inact 129292 purgeable 58712 spec 81788 cleaned 0nSep 9 09:06:37 Jies-MacBook-Air kernel[0]: WARNING: hibernate_page_list_setall skipped 47782 xpmapped pagesnSep 9 09:06:37 Jies-MacBook-Air kernel[0]: hibernate_page_list_setall preflight pageCount 225934 est comp 41 setfile 421527552 min 1073741824nSep 9 09:06:37 Jies-MacBook-Air kernel[0]: kern_open_file_for_direct_io(0)nSep 9 09:06:37 Jies-MacBook-Air kernel[0]: kern_open_file_for_direct_io took 181 msnSep 9 ' Traceback (most recent call last): File "/Users/jieli/PycharmProjects/python基础/自动化day8socket/sock_client.py",line 17,in total_rece_size = int(res_return_size) ValueError: invalid literal for int() with base 10: b'3472816Sep 9 09:06:37 Jies-MacBook-Air kernel[0]: hibernate image path: /var/vm/sleepimagenSep 9 09:06:37 Jies-MacBook-Air kernel[0]: efi pagecount 65nSep 9 09:06:37 Jies-MacBook-Air kernel[0]:

Process finished with exit code 1

看程序执行报错了, 我在客户端本想只接服务器端命令的执行结果,但实际上却连命令结果也跟着接收了一部分。 这是为什么呢???服务器不是只send了结果的大小么?不应该只是个数字么?尼玛命令结果不是第2次send的时候才发送的么??,擦,擦,擦,价值观都要崩溃了啊。。。。

答案就是:

  1. time.sleep(0.5),经多次测试,让服务器程序sleep 至少0.5就会造成缓冲区超时。哈哈哈, 你会说,擦,这么玩不会被老板开除么,虽然我们觉得0.5s不多,但是对数据实时要求高的业务场景,比如股票交易,过了0.5s 股票价格可以就涨跌很多,搞毛线呀。但没办法,我刚学socket的时候 找不到更好的办法,就是这么玩的,现在想想也真是low呀
  2. 但现在我是有Tesla的男人了,不能再这么low了, 所以推出nb新姿势就是, 不用sleep,服务器端每发送一个数据给客户端,就立刻等待客户端进行回应,即调用 conn.recv(1024),由于recv在接收不到数据时是阻塞的,这样就会造成,服务器端接收不到客户端的响应,就不会执行后面的conn.sendall(命令结果)的指令,收到客户端响应后,再发送命令结果时,缓冲区就已经被清空了,因为上一次的数据已经被强制发到客户端了。 好机智 , 看下面代码实现。
=

<span style="color: #0000ff;">import<span style="color: #000000;"> socket
<span style="color: #0000ff;">import<span style="color: #000000;"> os,9999)) <span style="color: #008000;">#<span style="color: #008000;">绑定ip port
server.listen() <span style="color: #008000;">#<span style="color: #008000;">开始监听

<span style="color: #0000ff;">while True: <span style="color: #008000;">#<span style="color: #008000;">第一层loop
<span style="color: #0000ff;">print(<span style="color: #800000;">"<span style="color: #800000;">等待客户端的连接...<span style="color: #800000;">"<span style="color: #000000;">)
conn,has not output!<span style="color: #800000;">".encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">"<span style="color: #000000;">)
conn.send(str(len(res)).encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">")) <span style="color: #008000;">#<span style="color: #008000;">发送数据之前,先告诉客户端要发多少数据给它
<span style="color: #0000ff;">print(<span style="color: #800000;">"<span style="color: #800000;">等待客户ack应答...<span style="color: #800000;">"<span style="color: #000000;">)
client_final_ack = conn.recv(1024) <span style="color: #008000;">#<span style="color: #008000;">等待客户端响应
<span style="color: #0000ff;">print(<span style="color: #800000;">"<span style="color: #800000;">客户应答:<span style="color: #800000;">"<span style="color: #000000;">,client_final_ack.decode())
<span style="color: #0000ff;">print<span style="color: #000000;">(type(res))
conn.sendall(res) <span style="color: #008000;">#<span style="color: #008000;">发送端也有最大数据量限制,直至数据发送完毕
<span style="color: #000000;">
server.close()

=

<span style="color: #0000ff;">import<span style="color: #000000;"> socket
<span style="color: #0000ff;">import<span style="color: #000000;"> sys

client =<span style="color: #000000;"> socket.socket()

client.connect((<span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",9999<span style="color: #000000;">))

<span style="color: #0000ff;">while<span style="color: #000000;"> True:
msg = input(<span style="color: #800000;">"<span style="color: #800000;">>>:<span style="color: #800000;">"<span style="color: #000000;">).strip()
<span style="color: #0000ff;">if len(msg) == 0:<span style="color: #0000ff;">continue<span style="color: #000000;">
client.send( msg.encode(<span style="color: #800000;">"<span style="color: #800000;">utf-8<span style="color: #800000;">"<span style="color: #000000;">) )

res_return_size  </span>= client.recv(1024) <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;接收这条命令执行结果的大小</span>
<span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;getting cmd result,res_return_size)
total_rece_size </span>=<span style="color: #000000;"&gt; int(res_return_size)
</span><span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;total size:</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,res_return_size)
client.send(</span><span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;准备好接收了,发吧loser</span><span style="color: #800000;"&gt;"</span>.encode(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;utf-8</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;))
received_size </span>= 0 <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;已接收到的数据</span>
cmd_res = b<span style="color: #800000;"&gt;''</span><span style="color: #000000;"&gt;
f </span>= open(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;test_copy.html</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;wb</span><span style="color: #800000;"&gt;"</span>)<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;把接收到的结果存下来,一会看看收到的数据 对不对</span>
<span style="color: #0000ff;"&gt;while</span> received_size != total_rece_size: <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;代表还没收完</span>
    data = client.recv(1024<span style="color: #000000;"&gt;)
    received_size </span>+= len(data) <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;为什么不是直接1024,还判断len干嘛,注意,实际收到的data有可能比1024少</span>
    cmd_res +=<span style="color: #000000;"&gt; data
</span><span style="color: #0000ff;"&gt;else</span><span style="color: #000000;"&gt;:
    </span><span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;数据收完了</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,received_size)
    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;print(cmd_res.decode())</span>
    f.write(cmd_res) <span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;把接收到的结果存下来,一会看看收到的数据 对不对</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt;print(data.decode()) #命令执行结果</span>

<span style="color: #000000;">
client.close()

6. SocketServer

The??module simplifies the task of writing network servers.

socketserver一共有这么几种类型

This uses datagrams,which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for?.

These more infrequently used classes are similar to the TCP and UDP classes,but use Unix domain sockets; they’re not available on non-Unix platforms. The parameters are the same as for?.

There are five classes in an inheritance diagram,four of which represent synchronous servers of four types:

| |

创建一个socketserver 至少分以下几步:

  1. First,you must create a request handler class by subclassing the?class and overriding its??method; this method will process incoming requests.?  
  2. Second,you must instantiate one of the server classes,passing it the server’s address and the request handler class.
  3. Then call the??or?method of the server object to process one or many requests.
  4. Finally,call??to close the socket.

基本的socketserver代码

<span style="color: #0000ff;">class<span style="color: #000000;"> MyTCPHandler(socketserver.BaseRequestHandler):
<span style="color: #800000;">"""<span style="color: #800000;">
The request handler class for our server.

It is instantiated once per connection to the server,and must
override the handle() method to implement communication to the
client.
</span><span style="color: #800000;"&gt;"""</span>

<span style="color: #0000ff;"&gt;def</span><span style="color: #000000;"&gt; handle(self):
    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; self.request is the TCP socket connected to the client</span>
    self.data = self.request.recv(1024<span style="color: #000000;"&gt;).strip()
    </span><span style="color: #0000ff;"&gt;print</span>(<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;{} wrote:</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;.format(self.client_address[0]))
    </span><span style="color: #0000ff;"&gt;print</span><span style="color: #000000;"&gt;(self.data)
    </span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; just send back the same data,but upper-cased</span>

<span style="color: #000000;"> self.request.sendall(self.data.upper())

<span style="color: #0000ff;">if <span style="color: #800080;">name == <span style="color: #800000;">"<span style="color: #800000;">main<span style="color: #800000;">"<span style="color: #000000;">:
HOST,PORT = <span style="color: #800000;">"<span style="color: #800000;">localhost<span style="color: #800000;">",9999

<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Create the server,binding to localhost on port 9999</span>
server =<span style="color: #000000;"&gt; socketserver.TCPServer((HOST,PORT),MyTCPHandler)

</span><span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; Activate the server; this will keep running until you</span>
<span style="color: #008000;"&gt;#</span><span style="color: #008000;"&gt; interrupt the program with Ctrl-C</span>
server.serve_forever()</pre>

但你发现,上面的代码,依然不能同时处理多个连接,擦,那我搞这个干嘛?别急,不是不能处理多并发,如果你想,你还要启用多线程,多线程我们现在还没讲,但你大体知道,有了多线程,就能同时让cpu干多件事了就行先。

让你的socketserver并发起来, 必须选择使用以下一个多并发的类

so 只需要把下面这句

换成下面这个,就可以多并发了,这样,客户端每连进一个来,服务器端就会分配一个新的线程来处理这个客户端的请求

server = socketserver.ThreadingTCPServer((HOST,MyTCPHandler)

server_address,?RequestHandlerClass

the superclass of all Server objects the module. It defines the interface,given below,but does implement most of the methods,which done subclasses. The two parameters are stored the respective server_address fileno()
Return an integer file descriptor
<span style="color: #0000ff;">for
the socket on which the server <span style="color: #0000ff;">is
listening. This function <span style="color: #0000ff;">is
most commonly passed to selectors,to allow monitoring multiple servers <span style="color: #0000ff;">in
<span style="color: #000000;"> the same process.

handle_request()
Process a single request. This function calls the following methods <span style="color: #0000ff;">in order: get_request(),verify_request(),<span style="color: #0000ff;">and process_request(). If the user-provided handle() method of the handler <span style="color: #0000ff;">class raises an exception,the server’s handle_error() method will be called. If no request <span style="color: #0000ff;">is received within timeout seconds,handle_timeout() will be called <span style="color: #0000ff;">and handle_request() will <span style="color: #0000ff;">return<span style="color: #000000;">.

serve_forever(poll_interval=0.5<span style="color: #000000;">)
Handle requests until an explicit shutdown() request. Poll <span style="color: #0000ff;">for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(),which may be used by a subclass <span style="color: #0000ff;">or mixin to provide actions specific to a given service. For example,the ForkingMixIn <span style="color: #0000ff;">class<span style="color: #000000;"> uses service_actions() to clean up zombie child processes.

Changed <span style="color: #0000ff;">in version 3.3<span style="color: #000000;">: Added service_actions call to the serve_forever method.

service_actions()
This <span style="color: #0000ff;">is called <span style="color: #0000ff;">in the serve_forever() loop. This method can be overridden by subclasses <span style="color: #0000ff;">or<span style="color: #000000;"> mixin classes to perform actions specific to a given service,such as cleanup actions.

New <span style="color: #0000ff;">in version 3.3<span style="color: #000000;">.

shutdown()
Tell the serve_forever() loop to stop <span style="color: #0000ff;">and<span style="color: #000000;"> wait until it does.

server_close()
Clean up the server. May be overridden.

address_family
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET <span style="color: #0000ff;">and<span style="color: #000000;"> socket.AF_UNIX.

RequestHandlerClass
The user-provided request handler <span style="color: #0000ff;">class; an instance of this <span style="color: #0000ff;">class <span style="color: #0000ff;">is created <span style="color: #0000ff;">for<span style="color: #000000;"> each request.

server_address
The address on which the server <span style="color: #0000ff;">is listening. The format of addresses varies depending on the protocol family; see the documentation <span style="color: #0000ff;">for the socket module <span style="color: #0000ff;">for details. For Internet protocols,this <span style="color: #0000ff;">is a tuple containing a string giving the address,<span style="color: #0000ff;">and an integer port number: (<span style="color: #800000;">'<span style="color: #800000;">127.0.0.1<span style="color: #800000;">',80),<span style="color: #0000ff;">for<span style="color: #000000;"> example.

socket
The socket object on which the server will listen <span style="color: #0000ff;">for<span style="color: #000000;"> incoming requests.

The server classes support the following <span style="color: #0000ff;">class<span style="color: #000000;"> variables:

allow_reuse_address
Whether the server will allow the reuse of an address. This defaults to False,<span style="color: #0000ff;">and can be set <span style="color: #0000ff;">in<span style="color: #000000;"> subclasses to change the policy.

request_queue_size
The size of the request queue. If it takes a long time to process a single request,any requests that arrive <span style="color: #0000ff;">while the server <span style="color: #0000ff;">is busy are placed into a queue,up to request_queue_size requests. Once the queue <span style="color: #0000ff;">is full,further requests <span style="color: #0000ff;">from clients will get a “Connection denied” error. The default value <span style="color: #0000ff;">is usually 5<span style="color: #000000;">,but this can be overridden by subclasses.

socket_type
The type of socket used by the server; socket.SOCK_STREAM <span style="color: #0000ff;">and<span style="color: #000000;"> socket.SOCK_DGRAM are two common values.

timeout
Timeout duration,measured <span style="color: #0000ff;">in seconds,<span style="color: #0000ff;">or None <span style="color: #0000ff;">if no timeout <span style="color: #0000ff;">is desired. If handle_request() receives no incoming requests within the timeout period,the handle_timeout() method <span style="color: #0000ff;">is<span style="color: #000000;"> 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.

finish_request()
Actually processes the request by instantiating RequestHandlerClass <span style="color: #0000ff;">and<span style="color: #000000;"> calling its handle() method.

get_request()
Must accept a request <span style="color: #0000ff;">from the socket,<span style="color: #0000ff;">and <span style="color: #0000ff;">return a 2-tuple containing the new socket object to be used to communicate with the client,<span style="color: #0000ff;">and<span style="color: #000000;"> the client’s address.

handle_error(request,client_address)
This function <span style="color: #0000ff;">is called <span style="color: #0000ff;">if the handle() method of a RequestHandlerClass instance raises an exception. The default action <span style="color: #0000ff;">is to <span style="color: #0000ff;">print the traceback to standard output <span style="color: #0000ff;">and <span style="color: #0000ff;">continue<span style="color: #000000;"> handling further requests.

handle_timeout()
This function <span style="color: #0000ff;">is called when the timeout attribute has been set to a value other than None <span style="color: #0000ff;">and the timeout period has passed with no requests being received. The default action <span style="color: #0000ff;">for forking servers <span style="color: #0000ff;">is to collect the status of any child processes that have exited,<span style="color: #0000ff;">while <span style="color: #0000ff;">in<span style="color: #000000;"> threading servers this method does nothing.

process_request(request,client_address)
Calls finish_request() to create an instance of the RequestHandlerClass. If desired,this function can create a new process <span style="color: #0000ff;">or thread to handle the request; the ForkingMixIn <span style="color: #0000ff;">and<span style="color: #000000;"> ThreadingMixIn classes do this.

server_activate()
Called by the server’s constructor to activate the server. The default behavior <span style="color: #0000ff;">for<span style="color: #000000;"> 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)
Must <span style="color: #0000ff;">return a Boolean value; <span style="color: #0000ff;">if the value <span style="color: #0000ff;">is True,the request will be processed,<span style="color: #0000ff;">and <span style="color: #0000ff;">if it’s False,the request will be denied. This function can be overridden to implement access controls <span style="color: #0000ff;">for a server. The default implementation always returns True.

作业:开发一个支持多用户在线的FTP程序

要求:

  1. 用户加密认证
  2. 允许同时多用户登录
  3. 每个用户有自己的家目录 ,且只能访问自己的家目录
  4. 对用户进行磁盘配额,每个用户的可用空间不同
  5. 允许用户在ftp server上随意切换目录
  6. 允许用户查看当前目录下文件
  7. 允许上传和下载文件,保证文件一致性
  8. 文件传输过程中显示进度条
  9. 附加功能:支持文件的断点续传

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读