Python Finishing-day9

Source: Internet
Author: User

1. TCP/IP

Full name of the TCP/IP protocol: Transmission Control Protocol and Internet Protocol

TCP/IP protocol is the standard of communication between host Internet and Internet access

1. Physical layer (physical layer) physical layer specifies the mechanical, electrical, functional, and process characteristics of activating, maintaining, and closing communication endpoints.    This layer provides a physical medium for the upper level protocol to transmit data.    In this layer, the unit of data is called the bit (bit).    Typical canonical representatives belonging to the physical layer definition include: Eia/tia RS-232, Eia/tia RS-449, v.35, RJ-45, etc. 2. The Data Link Layer Data link layer provides reliable transmission on unreliable physical media.    The functions of this layer include: Physical address addressing, data framing, flow control, data error checking, re-sending, etc.    In this layer, the units of the data are called frames.    The Data Link layer protocol includes: SDLC, HDLC, PPP, STP, Frame Relay, and so on. 3. Network Layer Network layer is responsible for routing the packets between subnets.    In addition, the network layer can also realize congestion control, Internet interconnection and other functions.    At this level, the unit of data is called a packet (packet).    Network layer protocol representatives include: IP, IPX, RIP, OSPF, and so on. 4, the Transport layer (Transport layer) Transport layer is the first end-to-end, that is, host-to-host hierarchy. The transport layer is responsible for segmenting the upper data and providing an end-to-end, reliable, or unreliable transmission.    In addition, the transport layer also handles end-to-end error control and flow control issues.    In this layer, the unit of data is called the Data segment (segment).    The Transport Layer protocol includes: TCP, UDP, SPX, and so on. 5. Session Layer Session layer manages the session between hosts, which is responsible for establishing, managing, and terminating sessions between processes.    The session layer also uses the insertion of checkpoints in the data to synchronize data.    The representative of the Session Layer protocol includes: NetBIOS, ZIP (AppleTalk Zone Information Protocol), etc. 6. The presentation layer (Presentation layer) represents layers that transform the upper data or information to ensure that one host application layer information can be understood by another host's application.    The data transformation of the presentation layer includes data encryption, compression, format conversion, and so on.    Representatives of the presentation layer protocol include: ASCII, ASN.1, JPEG, MPEG, and so on.  7. The Application layer (application layer) provides an interface for operating systems or network applications to access network services. The application layer protocol includes: Telnet, FTP, HTTP, SNMP, and so on.

We read the OSI7 layer model, we will think of the TCP/IP5 layer model, two are interlinked.

This is when we introduce the socket concept.

a Socket is a software abstraction layer that is only responsible for processing, but not sending data, and sending data through protocols .

The above diagram is the machine interaction through which the socket is implemented.

Some definitions of sockets:

1. python3.5.2 version-based sockets can only send and receive bytes (python2.7 can transmit str)

2. Exit is OK only when the client exits

3.s.accept () and S.RECV () are blocked (based on link OK)

4.listen (n) n represents: The number of links that can be suspended, if n=1, the delegate can link one, suspend one, and the third rejects

5. Port Conflict on server: Modify listening port number

6.

To serve the client:

1.send #数据长度

4.recv #收到确认信息, start next send

Send

Client:

2.recv #获取数据长度

3.send #发送确认信息

Recv #循环接收

Here we will take a program to learn:

Server-side programs:

Import socketip_port= (' 127.0.0.1 ', 9999) #必须是元组s =socket.socket () s.bind (Ip_port) S.listen (5) while True:    Conn, Addr=s.accept () while    True:        try:            rev_data=conn.recv (1024x768)            if Len (rev_data) ==0:break            send_ Data=rev_data.upper ()            print (send_data)            conn.send (send_data)        except Exception:    break Conn.close ()

Client side:

Import socketip_port= (' 127.0.0.1 ', 9999) #必须是元组s =socket.socket () s.connect (Ip_port) while True:    send_data=input ( ">>:"). Strip ()    if send_data = = "Exit": Break    If Len (send_data) ==0:continue    s.send (bytes (send_data , encoding= ' Utf-8 '))    recv_data=s.recv (1024x768)    print (str (recv_data,encoding= ' utf-8 ')) S.close ()

When I first run the server-side program, and then run the server-side program:

Through the program we can know that the function point is the client side of the input into uppercase and then return to the client side.

>>:lsls>>:llllll>>:

This is the client's input and return results, we look at the server side of the results:

B ' LS ' B ' LLL '

It can be seen that the variable type is byters

In the exit, we need to pay attention to a place, is to pause the client and then to stop the server side, the package will be newspapers the port occupies the error.

If you want to avoid this error, you can use the following code:

#1. Plus s.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1), #如下代码self. Host=socket.gethostbyname (Socket.gethostname ()) s = Socket.socket (socket.af_inet,socket . SOCK_STREAM) s.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) s.bind ((Self.host,self.port)) S.listen (5)

When the socket is programmed, the byte is sent, and when it is received, it does not need to be modified, which will return the received bytes directly.

Recv and accept these two places have blocked points (based on the connection is normal)

And look at a program.

The main function of this program is to transfer big data methods

Server side:

#!/usr/bin/env python#-*-coding:utf-8-*-# author:wzcimport socketimport subprocess #导入执行命令模块ip_port = (' 127.0.0.1 ', 9999) #定义元祖s =socket.socket () #绑定协议, raw complete socket S.bind (ip_port) #绑定ip + protocol + port: used to uniquely identify a process, ip_port must be a tuple format s.listen (5) #定义最大可 To suspend Hu Qin connection while True: #用来重复接收新的链接 conn,addr=s.accept () #接收客户端的链接请求, return conn (equivalent to a specific Hu Qin connection), addr is the client Ip+port #收消息 while True: #用来基于一个链接重复收发消息 Try: #捕捉客户端异常关闭 (Ctrl + C) RECV_DATA=CONN.RECV (1024x768) #收消息, Block I F len (recv_data) = = 0:break #客户端如果退出, the server will receive an empty message, exit the #发消息 p=subprocess. Popen (str (recv_data,encoding= ' UTF8 '), shell=true,stdout=subprocess.                                                                                                      PIPE) #执行系统命令, Windows flat                    The standard output of the # command is GBK encoded, need to convert res=p.stdout.read () #获取标准输出 If Len (res) = = 0: #执行错误命令, the standard output is empty, Send_data= ' cmd err ' else:send_data=str (res,encoding= ' GBK ')  #命令执行ok, byte GBK---->str----> Byte utf-8 send_data=bytes (send_data,encoding= ' UTF8 ') #解决粘包问题                ready_tag= ' ready|%s '%len (send_data) conn.send (bytes (ready_tag,encoding= ' UTF8 ')) #发送数据长度 FEEDBACK=CONN.RECV (1024x768) #接收确认信息 feedback=str (feedback,encoding= ' UTF8 ') if fee                Dback.startswith (' Start '): Conn.send (send_data) #发送命令的执行结果 except Exception: Break #挂电话 Conn.close ()

 client End:

#!/usr/bin/env python#-*-coding:utf-8-*-# Author:Alex Liimport socketip_ port= (' 127.0.0.1 ', 9999) #买手机s =socket.socket () #拨号s. Connect (ip_port) #链接服务端, if the service already has a good connection, suspend while True: #基于connec    T establishes the connection to loop the message send_data=input (">>:"). Strip () if send_data = = ' exit ': Break If Len (send_data) = = 0:continue S.send (bytes (send_data,encoding= ' UTF8 ')) #解决粘包问题 ready_tag=s.recv (1024x768) #收取带数据长度的字节: ready|9998 ready_tag=str (r eady_tag,encoding= ' UTF8 ') if Ready_tag.startswith (' Ready '): #Ready |9998 msg_size=int (ready_tag.split (' | ')  [-1]) #获取待接收数据长度 start_tag= ' start ' s.send (bytes (start_tag,encoding= ' UTF8 ')) #发送确认信息 #基于已经收到的待接收数据长度 and loop over the data recv_size =0 recv_msg=b "While Recv_size < Msg_size:recv_data=s.recv (1024x768) Recv_msg+=recv_data recv_ Size+=len (recv_data) print (' MSG size%s rece size%s '% (msg_size,recv_size)) print (str (recv_msg,encoding= ' UTF8 ') ) #挂电话s. Close () 

This program is to note that the place is "sticky bag"

On both sides of the send, if the time interval of two execution is not long, there will be a port occupied by the rear

Use multi-process:

Server Side

Python Finishing-day9

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.