python 自动化之路 day 08_2 网络编程

 

本节内容

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

 

 

1. Socket介绍

概念

 

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

For example, to send "Hello, world!" via TCP 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至少要分以下几步,(伪代码)

1
2
3
4
Socket socket = getSocket(type = "TCP")  #设定好协议类型
connect(socket, address = "1.2.3.4", port = "80"#连接远程机器
send(socket, "Hello, world!"#发送消息
close(socket) #关闭连接

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

socket address is the combination of an IP address and a port number, much like one end of a telephone connection is the combination of a phone number and a particular extension. 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 process or thread.

Socket Families(地址簇)

socket.AF_UNIX unix本机进程间通信 

socket.AF_INET IPV4 

socket.AF_INET6  IPV6

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

Socket Types

socket.SOCK_STREAM  #for tcp

socket.SOCK_DGRAM   #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 #废弃了

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

 

2. Socket 参数介绍

socket.socket(family=AF_INETtype=SOCK_STREAMproto=0fileno=None)  必会

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

socket.socketpair([family[, type[, proto]]])

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

socket.create_connection(address[, timeout[, source_address]])

Connect to a TCP service listening on the Internet address (a 2-tuple (host, port)), and return the socket object. This is a higher-level function than socket.connect(): if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6, 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 getdefaulttimeout() is used.

If supplied, source_address must be a 2-tuple (host, port) 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.

socket.getaddrinfo(hostportfamily=0type=0proto=0flags=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() 

  套接字的文件描述符

socket.sendfile(fileoffset=0count=None)

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

 

SocketServer

The socketserver module simplifies the task of writing network servers.

There are four basic concrete server classes:

class socketserver.TCPServer(server_addressRequestHandlerClassbind_and_activate=True)

This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. If bind_and_activate is true, the constructor automatically attempts to invoke server_bind() andserver_activate(). The other parameters are passed to the BaseServer base class.

class socketserver.UDPServer(server_addressRequestHandlerClassbind_and_activate=True)

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 TCPServer.

class socketserver.UnixStreamServer(server_addressRequestHandlerClassbind_and_activate=True)class socketserver.UnixDatagramServer(server_addressRequestHandlerClass,bind_and_activate=True)

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 TCPServer.

These four classes process requests synchronously; each request must be completed before the next request can be started. This isn’t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it returns a lot of data which the client is slow to process. The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour.

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

+------------+
| BaseServer |
+------------+| v +-----------+ +------------------+ | TCPServer |------->| UnixStreamServer | +-----------+ +------------------+ | v +-----------+ +--------------------+ | UDPServer |------->| UnixDatagramServer | +-----------+ +--------------------+ 

Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both Unix server classes.

class socketserver.ForkingMixInclass socketserver.ThreadingMixIn

Forking and threading versions of each type of server can be created using these mix-in classes. For instance, ThreadingUDPServer is created as follows:

class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass 

The mix-in class comes first, since it overrides a method defined in UDPServer. Setting the various attributes also changes the behavior of the underlying server mechanism.

class socketserver.ForkingTCPServerclass socketserver.ForkingUDPServerclass socketserver.ThreadingTCPServerclass socketserver.ThreadingUDPServer

These classes are pre-defined using the mix-in classes.

 

 

 

Request Handler Objects

class socketserver.BaseRequestHandler

This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle() method, and can override any of the other methods. A new instance of the subclass is created for each request.

setup()

Called before the handle() method to perform any initialization actions required. The default implementation does nothing.

handle()

This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information.

The type of self.request is different for datagram or stream services. For stream services,self.request is a socket object; for datagram services, self.request is a pair of string and socket.

finish()

Called after the handle() method to perform any clean-up actions required. The default implementation does nothing. If setup() raises an exception, this function will not be called.

 

 

 

socketserver.TCPServer Example

server side

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    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.
    """
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
if __name__ == "__main__":
    HOST, PORT = "localhost"9999
    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

client side

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import socket
import sys
HOST, PORT = "localhost"9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n""utf-8"))
    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")
finally:
    sock.close()
print("Sent:     {}".format(data))
print("Received: {}".format(received))

上面这个例子你会发现,依然不能实现多并发,哈哈,在server端做一下更改就可以了

1
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

改成

 

1
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

 

转载于:https://www.cnblogs.com/yangliheng/p/6106701.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/542162.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Elasticsearch过滤与聚合的先后顺序java实现

2019独角兽企业重金招聘Python工程师标准>>> 一、Elasticsearch的聚合 ES的聚合相当于关系型数据库里面的group by,例如查找在性别字段男女人数的多少并且按照人数的多少进行排序,在使用MySQL的时候,可以使用如下的句子 select se…

js手机号中间四位_11位手机号码隐藏中间四位数,学会Substitute函数一键搞定!...

相信许多朋友都有见过手机号码被*号隐藏中间四位数的情况。许多地方为了保护个人信息,都会将手机号的中间四位数用星号代替。如上图所示,我们需要将原来的手机号码,通过*号的方式变为隐藏后的加密模式。下面我们就来学习一下如何利用substitu…

python 整数最大_Python程序使用floor()方法查找最大整数

python 整数最大The greatest integer function is a function (real numbers function) to itself that is defined as follows: it sends any real number to the largest integer that is less than or equal to it. 最大整数函数是一个对其自身定义的函数(实数函数)&#x…

selinux对ftp的影响

1.啥是selinux 安全增强型Linux(Security-Enhanced Linux)简称selinux,它是一个Linux内核模块,也是Linux的一个安全子系统。 selinux的状态: Enforcing:强制模式,在selinux运作时,已经开始限制d…

ES6的class方法基本用法

为什么80%的码农都做不了架构师?>>> 在ES5中我们通常通过构造函数,定义并生成新对象。 例如: function Point(name,age){this.namename;this.ageage;}Point.prototype{Who:function(){return "My name is "this.name",My age…

celery的中文_celery异步任务框架

目录Celery一、官方二、Celery异步任务框架Celery架构图消息中间件任务执行单元任务结果存储三、使用场景四、Celery的安装配置五、两种celery任务结构:提倡用包管理,结构更清晰七、Celery执行异步任务包架构封装八、基本使用celery.py 基本配置tasks.py…

关于linux mv指令机制

最近在mv文件的时候,操作失误将生产服务器一个1TB的文件夹mv到了/opt/test目录,因为最后/opt/目录被沾满所以1TB的文件夹没有迁移过来,写入了30GB数据到了/opt/test目录,因为系统分区被沾满,所以把test目录给删除了。 …

数据库的管理

1. 数据库的简介 定义:数据库(Database)就是一种按数据结构来组织,存储和管理数据的仓库,其中包含数据挖掘,大数据信息的推送。 mariadb数据库管理系统是mysql的一个分支,主要由开源社区在维护&…

C#中的Dictionary字典类介绍(转载)

C#中的Dictionary字典类介绍 关键字:C# Dictionary 字典 作者:txw1958原文:http://www.cnblogs.com/txw1958/archive/2012/11/07/csharp-dictionary.html 说明 必须包含名空间System.Collection.Generic Dictionary里面的每一个元素都…

高速缓存dns

1. DNS: Domain Name System,域名系统。 万维网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网。他主要负责把域名和IP的相互转换,DNS运行与TCP|UDP的53端口上。 2. 高速缓存DNS:DNS服务…

Apache服务配置

1. apache 企业中常用的web服务。用来提供http://(超文本传输协议) 基础信息: 主配置目录: /etc/httpd/conf 主配置文件: /etc/httpd/conf/httpd.conf 子配置目录: /etc/httpd/conf.d/ 子配置文…

如何安装Genymotion虚拟机以及Genmotion的eclipse插件

---内容开始--- - 首先去genymotion的官网去下载其安装文件 资源下载 Genymotion官网必须注册一个账号这个账号安装之后还有用的,用户名最好用网易126邮箱注册----我下载的是2.8.0的版本(注:注册前先开个代理服务器不然页面打不开下载时最好用迅雷下载这…

squid服务配置(正向、反向代理)

代理: 就是代理网络用户去取得网络信息。 Squid是一种用来缓冲Internet数据的软件。安装Squid服务实现代理缓存服务器功能。 正向代理:意思是一个位于客户端和原始服务器之间的服务器,为了从原始服务器取得内容,客户端向代理发送一…

c语言getchar函数_C语言中带有示例的getchar()函数

c语言getchar函数C语言中的getchar()函数 (getchar() function in C) The getchar() function is defined in the <stdio.h> header file. getchar()函数在<stdio.h>头文件中定义。 Prototype: 原型&#xff1a; int getchar(void);Parameters: FILE *filename(f…

python及pycharm

1.python简介&#xff1a; Python是一种计算机程序设计语言。是一种动态的、面向对象的脚本语言&#xff0c;最初被设计用于编写自动化脚本(shell)&#xff0c;随着版本的不断更新和语言新功能的添加&#xff0c;越来越多被用于独立的、大型项目的开发。 python最重要的功能&am…

移动端适配方案(上)

转载自:https://github.com/riskers/blog/issues/17 要搞懂移动端的适配问题&#xff0c;就要先搞明白像素和视口。 像素 在移动端给一个元素设置 width:200px 时发生了什么&#xff1f;这里的px到底是多长呢&#xff1f;像素是网页布局的基础&#xff0c;但是我们一直在用直觉…

oracle sql 语句如何插入全年日期?

为什么80%的码农都做不了架构师&#xff1f;>>> oracle sql 语句如何插入全年日期&#xff1f; create table BSYEAR (d date); insert into BSYEAR select to_date(20030101,yyyymmdd)rownum-1 from all_objects where rownum < to_char(to_date(20031231,…

java基础——java基本运算

java基本运算 转载于:https://www.cnblogs.com/zhouj/p/6132535.html

【Java】MybatisPlus

MybatisPlus MybatisPlus是在mybatis基础上的一个增强型工具。它对mybatis的一些操作进行了简化&#xff0c;能够提高开发的效率。 springboot整合了mybatis之后&#xff0c;其实已经非常方便了&#xff0c;只需要导入mybatis的包后&#xff0c;在配置文件中编写数据源信息&a…

更新SQL Server实例所有数据库表统计信息

引出问题 自从上次菜鸟为老鸟解决了《RDS SQL SERVER 解决中文乱码问题》问题&#xff0c;老鸟意犹未尽&#xff0c;决定再想个招来刁难刁难菜鸟&#xff1a;“我最近做T-SQL性能调优的时候&#xff0c;经常发现执行计划中的统计信息不准确&#xff0c;导致SQL Server查询性能低…