【问题标题】:There a random 'b' that shouldn't be there [duplicate]有一个不应该存在的随机“b”[重复]
【发布时间】:2016-05-31 19:48:44
【问题描述】:

所以我在 python 中玩弄 UDP 通信,我终于得到了一些消息传递的工作,但在客户端,有一个随机的 'b' 这是我的代码

udpServer.py:

import socket
import time
import os
import getpass

userNonByt = getpass.getuser()
username = bytes(userNonByt, 'utf-8')
HOST = "localhost"
PORT =  5454
HOST = bytes(HOST, 'utf-8')
bytes(PORT)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

def setmsg():
    os.system('cls')
    #asks user for there text to send
    data = input("Send: ")
    #converts there text to bytes so it can be sent in the UDP Packet
    text = bytes(data, 'utf-8')
    #sends the users text
    s.sendto(username,(HOST,PORT))
    s.sendto((text),(HOST,PORT))
    #brings you back to the begining of this function
    setmsg()


setmsg()

udpClient.py:

import socket


HOST = 'localhost'
PORT =  5454
HOST = bytes(HOST, 'utf-8')

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

s.bind((HOST,PORT))

while 1:
    print (s.recv(30))

有人可以帮帮我吗?

【问题讨论】:

  • 切换到 Python 2.7,bb"...")将消失 ;-)
  • b"..." 仅表示它是 bytestring 而不是 unicode string ...
  • 递归不能替代循环。
  • 对“随机 b”的描述尤其缺乏信息。好在我们善于猜测,否则我们会在几个小时前关闭这篇文章。

标签: python udp


【解决方案1】:

您正在打印的内容是经过编码的。使用 .decode() 打印实际的字符串。

while 1:
    print(s.recv(30).decode())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    相关资源
    最近更新 更多