python 自動化之路 day 08_2 網絡編程

?

本節內容

  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?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)?#關閉連接

A?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.?  

A?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_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?AF_INET?(the default),?AF_INET6,?AF_UNIX,?AF_CAN?or?AF_RDS. The socket type should beSOCK_STREAM?(the default),?SOCK_DGRAM,?SOCK_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(host,?port,?family=0,?type=0,?proto=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()?

  套接字的文件描述符

socket.sendfile(file,?offset=0,?count=None)

? ? ?發送文件 ,但目前多數情況下并無什么卵用。

?

SocketServer

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

There are four basic concrete server classes:

class?socketserver.TCPServer(server_address,?RequestHandlerClass,?bind_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_address,?RequestHandlerClass,?bind_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_address,?RequestHandlerClass,?bind_and_activate=True)class?socketserver.UnixDatagramServer(server_address,?RequestHandlerClass,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.pswp.cn/news/542162.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542162.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542162.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

查看scala變量數據類型_Scala文字,變量和數據類型| Scala編程教程

查看scala變量數據類型1)Scala數據類型 (1) Scala Data Types) Scala has the same set of data types as in Java. The traditional 14 data types are inherited as it is in Scala. Scala具有與Java中相同的數據類型集。 傳統的14種數據類型在Scala中被繼承。 The Followin…

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里面的每一個元素都…

求階乘的第一個非零數字_查找數字階乘中的尾隨零

求階乘的第一個非零數字Problem statement: 問題陳述: Find the number of trailing zeros in n! (Where, n is the given input). 在n中找到尾隨零的數目! (其中, n是給定的輸入)。 Solution: 解: Computing a factorial is o…

高速緩存dns

1. DNS: Domain Name System,域名系統。 萬維網上作為域名和IP地址相互映射的一個分布式數據庫,能夠使用戶更方便的訪問互聯網。他主要負責把域名和IP的相互轉換,DNS運行與TCP|UDP的53端口上。 2. 高速緩存DNS:DNS服務…

python log日志級別_python – 日志記錄:如何為處理程序設置最大日志級別

您可以向文件處理程序添加過濾器.這樣,您可以將特定級別重定向到不同的文件.import loggingclass LevelFilter(logging.Filter):def __init__(self, low, high):self._low lowself._high highlogging.Filter.__init__(self)def filter(self, record):if self._low < recor…

Python Pandas –合并,聯接和串聯

There are three main ways to combine dataFrames i.e., merging, joining and concatenating. The following examples will illustrate merging, joining and concatenation. 組合dataFrames的主要方法有三種&#xff0c;即合并&#xff0c;聯接和串聯 。 以下示例將說明合并…

Apache服務配置

1. apache 企業中常用的web服務。用來提供http&#xff1a;//&#xff08;超文本傳輸協議&#xff09; 基礎信息&#xff1a; 主配置目錄&#xff1a; /etc/httpd/conf 主配置文件&#xff1a; /etc/httpd/conf/httpd.conf 子配置目錄&#xff1a; /etc/httpd/conf.d/ 子配置文…

git 怎么查看合并過來哪些代碼_git整理紛亂的歷史合并記錄

https://github.com/Epix37/Hearthstone-Deck-Tracker以上面版本庫的master分支為例父節點1SHA-1: a21142968282ae49720cf30a0f18290b2ce74b3a* remove hotkey from config if action could not be found, fix hotkey menu item name父節點2SHA-1: 86a824e8f46005db91f334dfc57…

如何安裝Genymotion虛擬機以及Genmotion的eclipse插件

---內容開始--- - 首先去genymotion的官網去下載其安裝文件 資源下載 Genymotion官網必須注冊一個賬號這個賬號安裝之后還有用的&#xff0c;用戶名最好用網易126郵箱注冊----我下載的是2.8.0的版本(注&#xff1a;注冊前先開個代理服務器不然頁面打不開下載時最好用迅雷下載這…

java system類_Java System類mapLibraryName()方法及示例

java system類系統類mapLibraryName()方法 (System class mapLibraryName() method) mapLibraryName() method is available in java.lang package. mapLibraryName()方法在java.lang包中可用。 mapLibraryName() method is used to map a given library name into a platform-…

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

代理&#xff1a; 就是代理網絡用戶去取得網絡信息。 Squid是一種用來緩沖Internet數據的軟件。安裝Squid服務實現代理緩存服務器功能。 正向代理&#xff1a;意思是一個位于客戶端和原始服務器之間的服務器&#xff0c;為了從原始服務器取得內容&#xff0c;客戶端向代理發送一…

家譜整站源碼php_mysql家譜表查詢某人所有后代

CREATE TABLE people (id INT(11) NOT NULL,name VARCHAR(50) NULL DEFAULT NULL,pid INT(11) NOT NULL DEFAULT 0,PRIMARY KEY (id));CREATE DEFINERroot% PROCEDURE getChildren(IN parentId INT)LANGUAGE SQLNOT DETERMINISTICCONTAINS SQLSQL SECURITY DEFINERCOMMENT 獲取…