socket programming of python

socket programming

socket

socket introduction

Socket is also called "socket". Applications usually send requests to the network or answer network requests through "socket", so that the host computer or the process on a computer can communicate with each other.

Use of socket

udp sending data

step

  • 1. Create socket
    • socket.socket([family[, type[, proto]]])
    • Family: socket family can make AF_UNIX or AF_INET
    • Type: socket type can be divided into sock based on whether it is connection oriented or non connection oriented_ Stream or SOCK_DGRAM
    • protocol: the default value is 0
    • Code example
      udp_s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
      
  • 2. Send data
    • sendto(self, data: bytes, address: _Address)
    • data: sent content, of type byte
    • Address: destination address, usually expressed in tuples
    • Code example
      udp_s.sendto(b'hello', ('192.168.1.3', 8080))
      
  • 3. Close socket
  • Code example
    udp_s.close()
    

Full presentation

import socket


def sendto():
    # 1. Create socket
    udp_s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    # 2. Send data
    while True:
        content = input("Please enter what you want to send:")
        # Default input q to exit chat
        if content == 'q':
            break
        # Convert the string to gbk code. The default is gbk code in windows system
        content = content.encode('gbk')
        udp_s.sendto(content, ('192.168.1.3', 8080))
        # 3. Close socket
    udp_s.close()


if __name__ == '__main__':
    sendto()

Note: before sending data, the sent string should be converted to gbk code, because for windows system, gbk code is the default

udp receiving data

step

  • 1. Create socket
    • Code example
          udp_s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
      
  • 2. Bind local window
    • Code example
      	addr = ('', 49871)  # First parameter default local ip address
      	udp_s.bind(addr)
      
  • 3. Receive data and print
    • Code example
      	data = udp_s.recvfrom(1024)  # 1024 Max bytes
          infos, from_addr = data  # Unpacking, obtaining data and user address
          print(f"{from_addr}: {infos}")  # Print information
      
  • 4. Close socket
    • Code example
      udp_s.close()
      

Full demo

import socket
def receive():
    # 1. Create socket
    udp_s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    # 2. Bind local port
    addr = ('', 49871)  # First parameter default local ip address
    udp_s.bind(addr)
    # 3. Receive data and print
    data = udp_s.recvfrom(1024)  # 1024 Max bytes
    infos, from_addr = data  # Unpacking, obtaining data and user address
    print(f"{from_addr}: {infos}")  # Print information
    # 4. Close socket
    udp_s.close()


if __name__ == '__main__':
    receive()

udp chat

step

  • 1. Create socket socket to send and receive data
  • 2. Send data
  • 3. Receiving data
  • 4. Close socket

Because the code of sending and receiving data is given above, it will be explained step by step and directly put into the code
Code example

import socket


def sendto(udp_s):
   # send data
   content = input("Please enter what you want to send:")
   # Convert the string to gbk code. The default is gbk code in windows system
   content = content.encode('gbk')
   udp_s.sendto(content, ('192.168.1.3', 8080))


def receive(udp_s):

   # Receive data and print
   data = udp_s.recvfrom(1024)  # 1024 Max bytes
   infos, from_addr = data  # Unpacking, obtaining data and user address
   print(f"{from_addr}: {infos}")  # Print information


def main():
   # 1. Create socket
   udp_s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

   # 2. Bind local port
   addr = ('', 49871)  # First parameter default local ip address
   udp_s.bind(addr)

   while True:
       # 3. Send data
       sendto(udp_s)

       # 4. Receive data
       receive(udp_s)

   # 5. Close socket
   udp_s.close()


if __name__ == '__main__':
   main()

Finally, a blogger like to write about the content of the partner can point like collection and attention Oh!

Tags: socket Windows network Programming

Posted on Fri, 26 Jun 2020 01:49:55 -0400 by mclordgt