程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Based on python3 network

編輯:Python

Network programming

  • The Internet :

  • Network protocol : A set of rules

  • Network model seven layer model - Seven layers The physical layer Data link layer The network layer Transport layer The session layer The presentation layer Application layer four layer model The link layer The network layer Transport layer application layer

  • Each layer has its own protocol for information exchange or collaboration

  • TCP/IP agreement Protocol family

  • IP Address : Responsible for locating the only machine on the network IP The address is divided into 5 class 3 spot 4 Paragraph style , Each field is 0~255127.0.0.1: This machine IPV4 IPV6

  • Port number range :0-65535 Well known ports :0——1023 Already known ports Unknown port :1024->

TCP/UDP agreement

  • UDP: Non secure, non link oriented transport

    • Poor safety

    • Size limit 64kb

    • There is no order

    • Fast

  • TCP

    • Link based communication

  • SOCKET Programming

    • socket( Socket ): This is an endpoint for network communication , Realize the process communication of different hosts

    • adopt IP+ The communication mechanism by which ports locate each other and send messages

    • It is divided into UDP and TC P

  • UDP Programming Server End process

    • 1. establish socket.socket Is an example of a specific communication

    • 2. binding , Create for socket Assign fixed ports and IP Address

    • 3. Accept the content sent by the other party

    • 4. Send feedback ,

    • This step is not required Client End process :

      • 1. Establish communication socket

      • 2. Send content to the specified server 3

      • . Receive feedback from the server

      • Server case V01

      • import socket
        def serverFunc():
        #AF_INET Use IPv4 agreement SOCK_DGRAM Use UDP agreement
        soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        # binding IP And port number
        addr = ('127.0.0.1',10089)
        soc.bind(addr)
        # Be interviewed
        data,addr = sco.recvfrom(500)
        print(data)
        # The data needs to be decoded before it can be read
        data = data.deconde()
        print(data)
        # Feedback to the other person
        res = ' Feedback '
        # Encode and send the data
        res = res.encode()
        soc.sendto(res,addr)
        if __name__ == "__main__":
        print('Start Server...')
        serverFunc()
        print('End Server.....')
        

         

      • Client case V02

      • import socket
        def clientFunc():
        soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        text = ' Access from the client '
        data = text.encode()
        soc.sendto(data,('127.0.0.1',10089))
        data,addr = socket.recvfrom(200)
        data = data.decode()
        print(data)
        if __name__ == '__main__':
        print("client...")
        clientFunc()
        print("end client...")

         

      • The server requires a permanent run case V03

        import socket
        import time
        def serverFunc():
        soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        addr = ('127.0.0.1',10089)
        soc.bind(addr)
        data,addr = soc.recvfrom(500)
        data = data.decode()
        print(data)
        res = ' Feedback from the server '
        res = res.encode()
        soc.sendto(res,addr)
        if __name__ == '__main__':
        print('Start Server..')
        while True:
        try:
        serverFunc()
        except Exceptiom as e:
        print(e)
        time.sleep(1)
        print('end Server...')
      •  

  • TCP Programming

    • Link oriented transport , And the connection needs to be established before each transmission

      • Both client and server programs need to be written

      • Server End of the writing process :

        • 1. establish socket Responsible for specific communications , This socket In fact, it is only responsible for accepting the request of the other party

        • 2. Bind port number and address

        • 3. Monitor access socket

        • 4. Visited socket, It is understandable that accepting access establishes a communication connection .

        • 5. Accept the content sent by the other party , Use what you receive socket Receiving content

        • 6. If necessary , Send feedback

        • 7. Close links

        • # Import package
          import socket
          def TCP_Server():
          #AF_INET Use IPV4 agreement ,SOC_STREAM Use TCP
          soc = socket.socket(socket.AF_INET,sockey.SOC_STREAM)
          addr = ('127.0.0.1',10089)
          # Binding address and port number
          soc.bind(addr)
          # Monitor the network
          soc.listen()
          while True:
          # The return value is the content and link address
          skt,addr = soc.accept()
          msg = skt.recv(500)
          data = msg.decode()
          rest = "recvide msg : {0} from {1}".formate(data,addr)
          print(rest)
          skt.send(rest.encode())
          skt.close()
          if __name__ == "__main__":
          print("Start Server...")
          TCP_Server()
          

           

      • Client End process :

        • 1. Establishing communication socket

        • 2. Link to each other , Request remote link with the other party

        • 3. Send content to the other server

        • 4. Accept feedback from others

        • 5. Close the connection case of the link V04 V05

        • import socket
          def TCP_Clinet():
          sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          addr = ('127.0.0.1',10089)
          scok.bind(addr)
          msg = " This is one hop client information "
          sock.send(msg.encode)
          res = sock.recv(500)
          print(res.decode)
          sock.close()
          if __name__ == "__main__":
          TCP_Client()

           

FTP Programming

  • FTP(FileTransferProtocal) File transfer protocol

  • purpose : Customize some special services for loading and downloading files

  • The user classification : land FTP The server needs an account

    • Real: Account

      • Guest: It can authorize the behavior of a certain class of people temporarily

      • Anonymous: Anonymous accounts , Allow anyone to .

  • FTP Workflow

    • The client Links... On the remote host FTP The server

    • The client enters the user name and password ( perhaps “anonymous” And email address )

    • Client and server carry out various file transfer and information query operations

    • Client from remote server FTP sign out , End transmission

  • FTP Representation of documents

    • In three paragraphs FTP Files on the server

    • HOST: The host address , Be similar to ftp.mozilla.org, With FTP start

    • DIR: Directory indicates the local path where the file is located

    • File: File name

    • If you want a complete and accurate representation ftp Last file , The above three parts need to be combined .- Case study V06

    • # Import the corresponding package
      import ftplib
      import os
      import socket
      # The three steps represent precise ftp A file on the server
      HOST = 'ftp.acc.umu.se'
      DIR = 'Public/EFLIB/'
      FILE = 'README'
      # Remote Links FTP The server
      try:
      f = ftplib.FTP()
      f.set_debuglevel(2)
      f,connect(HOST)
      except Exception as e:
      print(e)
      exit()
      print("******Connect to hsot {0}".formate(HOST))
      # Login server
      try:
      f.login()
      except Expetion as e:
      print(e)
      exit()
      print("login in sa 'anonymouse'")
      # Change the current directory after successful login
      try:
      f.cwd(DIR)
      except Exception as e:
      print(e)
      exit()
      print("***change dir to {0}".formate(DIR))
      # Download the corresponding file after switching directories
      try:
      # from FTP Download files on
      # The first parameter is FTP command
      # The second parameter is the callback function
      # This function must refer to , perform RETR command , After downloading the file to the local , Running callback function
      f.retrbinary('RETR {0}'.formate(FILE),open(FILE,"wb").write)
      except Exception as e:
      print(e)
      exit()
      # Link out
      f.quit()
      

       


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved