UDP通信

UDP通信思考为代码部分

  • 服务端
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# file: server.py
# author: wangchenxi
# mail: wongchenxi@icloud.com
# brief:
# version: 0.1.00
# Create Time:2021-03-21 22:37:28
# Last Update: 2021-03-21 22时47分34秒
import socket
global recieve_data
recieve_data = {}
START_SIGN = 'udp'
SS_LEN = len(START_SIGN)
DATA_LEN_SIGN_LEN = 10
UDP_MIN_LEN = DATA_LEN_SIGN_LEN + len(START_SIGN)
import queue
statistic_queue = queue()


def deal_data(data, addr):
    data_list = None
    if data and addr:  
        if addr not in recieve_data:
            data_list = list()
            data_list.extend(data)
            recieve_data[addr] = data_list
        else:
            data_list = recieve_data[addr]
            data_list.extend(data)

        data_list_len = len(data_list)

        while data_list and data_list_len > UDP_MIN_LEN:
            if ''.join[0:SS_LEN] == START_SIGN:
                data_len = int(''.join(data_list[SS_LEN:UDP_MIN_LEN]))
                message_len = UDP_MIN_LEN + data_len
                if len(data_list) >= message_len:
                    data_target = data_list[UDP_MIN_LEN:message_len]
                    statistic_queue.put(data_target)
                    data_list = data_list[message_len:]
                else:
                    break
            else:
                data_list = data_list[SS_LEN:]

            data_list_len = len(data_list)



def udp_server_run():
    udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    # AF_INET 表示使用IPv4, SOCK_DGRAM 则表明数据将是数据报(datagrams),
    # 对应 TCP 的是 SOCK_STREAM 表明数据对象是字节流(stream)
    udp.bind(('127.0.0.1', 8000))

    while True:
        try:
            data, addr = udp.recvfrom(1024)  # 返回数据以及发送数据的地址
            print(data.decode('utf-8'), addr)
            deal_data(data, addr)
            udp.sendto('server accept: '.encode('utf-8') + data, addr)  # 数据和对应的地址
        except Exception as e:
            print(e)
    udp.close()

if __name__ == '__main__':
    udp_server_run()
  • 客户端
  #! /usr/bin/python3
  # -*- coding:utf-8 -*-
  # file: client.py
  # author: wangchenxi
  # mail: wongchenxi@icloud.com
  # brief:
  # version: 0.1.00
  # Create Time:2021-03-21 22:40:06
  # Last Update: 2021-03-21 22时41分03秒
  import socket

  udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  while 1:
      msg = input("enter your msg>>:")
      udp_client.sendto(msg.encode('utf-8'), ('127.0.0.1', 8000))
      print(udp_client.recv(1024).decode('utf-8'))

版权声明:除特别注明外,本站所有文章均为王晨曦个人站点原创

转载请注明:出处来自王晨曦个人站点 » UDP通信

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

  1. jvwvhdtqsr 说道:

    出发地 ajvwvhdtqsr [url=http://www.g3eltgc4l23ir87r235ot461lbt5u231s.org/]ujvwvhdtqsr[/url] jvwvhdtqsr http://www.g3eltgc4l23ir87r235ot461lbt5u231s.org/