• 3 python3 编码解码问题 upd接受数据


    1.python3下的中文乱码:send_data.encode("utf-8")

    from socket import *
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    
    dest_ip = input("请输入目的ip:")
    dest_port  = int(input("请输入目的port:"))
    send_data = input("请输入要发送的数据:")
    
    udp_socket.sendto(send_data.encode("utf-8"),("192.168.123.1",dest_port))
    python@ubuntu:~/python06/07-网络编程$ python3 06-python3编码问题.py 请输入目的ip:192.168.123.1
    请输入目的port:8080
    请输入要发送的数据:hello 你好

     2.软件是gb2312编码格式的   send_data.encode("gb2312")

    from socket import *
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    
    dest_ip = input("请输入目的ip:")
    dest_port  = int(input("请输入目的port:"))
    send_data = input("请输入要发送的数据:")
    
    #udp_socket.sendto(send_data.encode("utf-8"),("192.168.123.1",dest_port))
    udp_socket.sendto(send_data.encode("gb2312"),("192.168.123.1",dest_port))

     

    3.元组解包,upd接受数据

    In [2]: a = (111,222)
    
    In [3]: b,c = a
    
    In [4]: b
    Out[4]: 111
    
    In [5]: c
    Out[5]: 222
    from socket import *
    
    updSocket = socket(AF_INET,SOCK_DGRAM)
    updSocket.bind(("",7789))
    
    recvData = updSocket.recvfrom(1024)
    
    content,destInfo = recvData
    print(recvData)
    print("content is %s"%content)
    print("content is %s"%content.decode("gb2312"))

         

        

    ##等待接受数据
    python@ubuntu:~/python06/07-网络编程$ python3 07-python3解码问题.py ('192.168.123.1', 8080)
    content is b'hello world'
    content is hello world
    
    ##等待接受数据
    python@ubuntu:~/python06/07-网络编程$ python3 07-python3解码问题.py 
    (b'xc4xe3xbaxc3xa3xacxb2xcbxc4xf1', ('192.168.123.1', 8080))
    content is b'xc4xe3xbaxc3xa3xacxb2xcbxc4xf1'
    content is 你好,菜鸟

    4.编码encode  解码decode

    ##对于要发送的数据,编码
    sendData = "123"
    
    udpSocket.sendto(sendData.encode("utf-8"))
    
    
    #对于接受来的数据,要进行解码
    recvData = xxx.recvfrom(1024)
    a,b = recvData
    #a = recvData[0]
    
    recvData[0].decode("gb2312")

    5.例子

        

    In [10]: n = "你好"
    
    In [11]: n.encode("gb2312")
    Out[11]: b'xc4xe3xbaxc3'
    
    In [12]: b = n.encode("gb2312")
    
    In [13]: n
    Out[13]: '你好'
    
    In [14]: b
    Out[14]: b'xc4xe3xbaxc3'
    
    In [15]: b.decode()
    
    ---------------------------------------------------------------------------
    UnicodeDecodeError                        Traceback (most recent call 
    
    In [16]: b.decode("utf-8")
    ---------------------------------------------------------------------------
    UnicodeDecodeError                        Traceback (most recent call 
    
    
    In [17]: b.decode("gb2312")
    Out[17]: '你好'
  • 相关阅读:
    Hdu 1257最少拦截系统
    删除mysql__转
    sql 入门的小例子熟悉一下_这可是一个转转转贴 :)
    header 用法_转
    java_json 转换 文件在file中
    javascript_php 正则匹配 转
    mysql 忘记密码转_kinghu
    php 通用下载
    明天就是新年开始
    翻译 有助于程序命名
  • 原文地址:https://www.cnblogs.com/venicid/p/7977258.html
Copyright © 2020-2023  润新知