Python-socket communication

Socket development history and classification

Sockets originated in the 1970s at the University of California, Berkeley version of Unix, or BSD Unix. Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets". In the beginning, sockets were designed to communicate between multiple applications on the same host. This is also known as inter-process communication, or IPC. There are two kinds of sockets (or called two races), which are file-based and network-based.

Socket family based on file type-AF_UNIX

Socket family name: AF_UNIX

Everything in Unix is ​​a file. The file-based socket calls the underlying file system to fetch data. Two socket processes run on the same machine and can communicate indirectly by accessing the same file system.

Socket family based on network type-AF_INET

Socket family name: AF_INET

(Also AF_INET6 is used for ipv6, and there are some other address families, but they are either only used for a certain platform, or are either abandoned, or rarely used, or not implemented at all, all addresses In the family, AF_INET is the most widely used one. Python supports many address families, but since we only care about network programming, most of the time we only use AF_INET)

socket () module function usage

 1 import socket
 2 socket.socket(socket_family,socket_type,protocal=0)
 3 socket_family 可以是 AF_UNIX 或 AF_INET。socket_type 可以是 SOCK_STREAM 或 SOCK_DGRAM。protocol 一般不填,默认值为 0。
 4 
 5 获取tcp/ip套接字
 6 tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 7 
 8 获取udp/ip套接字
 9 udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
10 
11 由于 socket 模块中有太多的属性。我们在这里破例使用了'from module import *'语句。使用 'from socket import *',我们就把 socket 模块里的所有属性都带到我们的命名空间里了,这样能 大幅减短我们的代码。
12 例如tcpSock = socket(AF_INET, SOCK_STREAM)

Server socket function

  • s.bind () binds (host, port number) to the socket
  • s.listen () starts TCP listening
  • s.accept () passively accepts TCP client connections, (blocking) waiting for the arrival of the connection

Client socket functions

  • s.connect () actively initiates TCP server connection
  • s.connect_ex () An extended version of the connect () function, which returns an error code when an error occurs instead of throwing an exception

Socket functions for public use

'''
s.recv()            接收TCP数据
s.send()            发送TCP数据(send在待发送数据量大于己端缓存区剩余空间时,数据丢失,不会发完)
s.sendall()         发送完整的TCP数据(本质就是循环调用send,sendall在待发送数据量大于己端缓
存区剩余空间时,数据不丢失,循环调用send直到发完)
s.recvfrom()        接收UDP数据
s.sendto()          发送UDP数据
s.getpeername()     连接到当前套接字的远端的地址
s.getsockname()     当前套接字的地址
s.getsockopt()      返回指定套接字的参数
s.setsockopt()      设置指定套接字的参数
s.close()           关闭套接字
'''

Lock-oriented socket method

  • s.setblocking () sets the blocking and non-blocking modes of the socket
  • s.settimeout () sets the timeout for blocking socket operations
  • s.gettimeout () Get the timeout of blocking socket operation

File-oriented socket functions

  • s.fileno () socket file descriptor
  • s.makefile () creates a file related to the socket

Socket communication based on tcp protocol

img

Let's start with the server. The server first initializes the Socket, then binds to the port (bind), listens to the port (listen), calls accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (connect), if the connection is successful, then the connection between the client and the server is established. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection.

  • Simple socket communication based on tcp protocol

    • tcp server

      import socket
      
      # 1、买手机
      phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 流式协议=》tcp协议
      
      # 2、绑定手机卡
      phone.bind(('127.0.0.1',8081)) # 0-65535, 1024以前的都被系统保留使用
      
      # 3、开机
      phone.listen(5) # 5指的是半连接池的大小
      print('服务端启动完成,监听地址为:%s:%s' %('127.0.0.1',8080))
      # 4、等待电话连接请求:拿到电话连接conn
      conn,client_addr=phone.accept()
      # print(conn)
      print("客户端的ip和端口:",client_addr)
      
      # 5、通信:收\发消息
      data=conn.recv(1024) # 最大接收的数据量为1024Bytes,收到的是bytes类型
      print("客户端发来的消息:",data.decode('utf-8'))
      conn.send(data.upper())
      
      # 6、关闭电话连接conn(必选的回收资源的操作)
      conn.close()
      
      # 7、关机(可选操作)
      phone.close()
      
    • tcp client

      import socket
      
      #1、买手机
      phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 流式协议=》tcp协议
      
      #2、拨通服务端电话
      phone.connect(('127.0.0.1',8081))
      
      #3、通信
      import time
      time.sleep(10)
      phone.send('hello egon 哈哈哈'.encode('utf-8'))
      data=phone.recv(1024)
      print(data.decode('utf-8'))
      
      #4、关闭连接(必选的回收资源的操作)
      phone.close()
      
  • Plus communication loop

    • tcp server

      import socket
      
      # 1、买手机
      phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 流式协议=》tcp协议
      
      # 2、绑定手机卡
      phone.bind(('127.0.0.1',8083)) # 0-65535, 1024以前的都被系统保留使用
      
      # 3、开机
      phone.listen(5) # 5指的是半连接池的大小
      print('服务端启动完成,监听地址为:%s:%s' %('127.0.0.1',8080))
      
      # 4、等待电话连接请求:拿到电话连接conn
      conn,client_addr=phone.accept()
      
      # 5、通信:收\发消息
      while True:
          try:
              data=conn.recv(1024) # 最大接收的数据量为1024Bytes,收到的是bytes类型
              if len(data) == 0:
                  # 在unix系统洗,一旦data收到的是空
                  # 意味着是一种异常的行为:客户度非法断开了链接
                  break
              print("客户端发来的消息:",data.decode('utf-8'))
              conn.send(data.upper())
          except Exception:
              # 针对windows系统
              break
      
      # 6、关闭电话连接conn(必选的回收资源的操作)
      conn.close()
      
      # 7、关机(可选操作)
      phone.close()
      
    • tcp client

      import socket
      
      #1、买手机
      phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 流式协议=》tcp协议
      
      #2、拨通服务端电话
      phone.connect(('127.0.0.1',8083))
      
      #3、通信
      while True:
          msg=input("输入要发送的消息>>>: ").strip() #msg=''
          if len(msg) == 0:continue
          phone.send(msg.encode('utf-8'))
          print('======?')
          data=phone.recv(1024)
          print(data.decode('utf-8'))
      
      #4、关闭连接(必选的回收资源的操作)
      phone.close()
      
    • Plus link loop

      tcp client

      # 服务端应该满足的特点:
      # 1、一直提供服务
      # 2、并发地提供服务
      import socket
      
      # 1、买手机
      phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 流式协议=》tcp协议
      
      # 2、绑定手机卡
      phone.bind(('127.0.0.1',8080)) # 0-65535, 1024以前的都被系统保留使用
      
      # 3、开机
      phone.listen(5) # 5指的是半连接池的大小
      print('服务端启动完成,监听地址为:%s:%s' %('127.0.0.1',8080))
      
      # 4、等待电话连接请求:拿到电话连接conn
      # 加上链接循环
      while True:
          conn,client_addr=phone.accept()
      
          # 5、通信:收\发消息
          while True:
              try:
                  data=conn.recv(1024) # 最大接收的数据量为1024Bytes,收到的是bytes类型
                  if len(data) == 0:
                      # 在unix系统洗,一旦data收到的是空
                      # 意味着是一种异常的行为:客户度非法断开了链接
                      break
                  print("客户端发来的消息:",data.decode('utf-8'))
                  conn.send(data.upper())
              except Exception:
                  # 针对windows系统
                  break
      
          # 6、关闭电话连接conn(必选的回收资源的操作)
          conn.close()
      
      # 7、关机(可选操作)
      phone.close()
      

Socket communication based on udp protocol

  • udp client

    import socket
    
    client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 流式协议=》tcp协议
    
    while True:
        msg=input('>>>: ').strip()
        client.sendto(msg.encode('utf-8'),('127.0.0.1',8081))
        res=client.recvfrom(1024)
        print(res)
    
    client.close()
    
  • udp server

    import socket
    
    server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议=》udp协议
    
    server.bind(('127.0.0.1',8081))
    
    while True:
        data,client_addr=server.recvfrom(1024)
        server.sendto(data.upper(),client_addr)
    
    server.close()
    

Guess you like

Origin www.cnblogs.com/guanxiying/p/12738774.html