Python3 Socket TypeError: a bytes-like object is required, not 'str' 錯誤提示

来源:https://www.cnblogs.com/weizt/archive/2018/02/08/8432915.html
-Advertisement-
Play Games

目前正在學習python基本語法以及電腦網路課,所以正好結合學習python網路編程,看的是《python核心編程》第三版,發現示例2-1代碼返回錯誤…..糾結很久 發現這裡python3.5和Python2.7在套接字返回值解碼上有區別。 先介紹一下 python bytes和str兩種類型轉換 ...


目前正在學習python基本語法以及電腦網路課,所以正好結合學習python網路編程,看的是《python核心編程》第三版,發現示例2-1代碼返回錯誤…..糾結很久
發現這裡python3.5和Python2.7在套接字返回值解碼上有區別。
先介紹一下 python bytes和str兩種類型轉換的函數encode(),decode()

  • str通過encode()方法可以編碼為指定的bytes
  • 反過來,如果我們從網路或磁碟上讀取了位元組流,那麼讀到的數據就是bytes。要把bytes變為str,就需要用decode()方法:

python核心編程書中的2-1例子

TCP伺服器:

#coding=utf-8
#創建TCP伺服器
from socket import *
from time import ctime

HOST=''
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

tcpSerSock=socket(AF_INET,SOCK_STREAM) #創伺服器套接字
tcpSerSock.bind(ADDR) #套接字與地址綁定
tcpSerSock.listen(5)  #監聽連接,傳入連接請求的最大數

while True:
    print('waiting for connection...')
    tcpCliSock,addr =tcpSerSock.accept()
    print('...connected from:',addr)

    while True:
        data =tcpCliSock.recv(BUFSIZ)
        #print('date=',data)
        if not data:
            break
        tcpCliSock.send(('[%s] %s' %(ctime(),data)))

    tcpCliSock.close()
tcpSerSock.close()

TCP客戶端

#coding=utf-8

from socket import *

HOST = 'localhost' #  or 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR=(HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = input('> ')
    print('data=',data);
    if not data:
        break
    tcpCliSock.send(data)
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    print(data)

tcpCliSock.close() 

返回的錯誤提示:
TypeError: a bytes-like object is required, not ‘str’
指的是18行tcpCliSock.send(data)傳入的參數是應該是bytes類型,而不是str類型。

於是我去百度,發現在StackOverflow上發現有人也出現同樣的問題,並一個叫Scharron的人提出瞭解答:

In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings.

So, now, whenever you have a unicode stringthat you need to use as a byte string, you need toencode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string.

Unicode strings are quotes enclosedstrings. Bytes strings are b”” enclosed strings

When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode()

於是我去查python3.5的幫助手冊。

socket.send(bytes[, flags])

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.recv(bufsize[, flags])

Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

Note

For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

修正後:

tcp伺服器

#coding=utf-8
#創建TCP伺服器
from socket import *
from time import ctime

HOST=''
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

tcpSerSock=socket(AF_INET,SOCK_STREAM) #創伺服器套接字
tcpSerSock.bind(ADDR) #套接字與地址綁定
tcpSerSock.listen(5)  #監聽連接,傳入連接請求的最大數

while True:
    print('waiting for connection...')
    tcpCliSock,addr =tcpSerSock.accept()
    print('...connected from:',addr)

    while True:
        data =tcpCliSock.recv(BUFSIZ).decode()
        print('date=',data)
        if not data:
            break
        tcpCliSock.send(('[%s] %s' %(ctime(),data)).encode())

    tcpCliSock.close()
tcpSerSock.close()

tcp客戶端:

#coding=utf-8

from socket import *

HOST = 'localhost' #  or 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR=(HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = input('> ')
    #print('data=',data);
    if not data:
        break
    tcpCliSock.send(data.encode())
    data = tcpCliSock.recv(BUFSIZ).decode()
    if not data:
        break
    print(data)

tcpCliSock.close()

socket.sendto(bytes, address)
socket.sendto(bytes, flags, address)

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.recvfrom(bufsize[, flags])

  Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

同理修正udp伺服器:

from socket import *
from time import ctime
HOST=''
PORT=21546
BUFSIZ=1024
ADDR=(HOST,PORT)

udpSerSock = socket(AF_INET,SOCK_DGRAM)
udpSerSock.bind(ADDR)

while True:
    print('waiting for message...')
    data,addr=udpSerSock.recvfrom(BUFSIZ)
    data=data.decode()
    udpSerSock.sendto(('[%s] %s'%(ctime(),data)).encode(),addr)
    print('...received from and returned to:',addr)

udpSerSock.close()
原博:http://blog.csdn.net/yexiaohhjk/article/details/68066843
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、整體流程 1、客戶端註冊Watcher 2、服務端處理Watcher 3、客戶端回調Watcher 二、Watcher 通知狀態與事件類型 state type path WatcheEvent 只有三個屬性 state type path 不會告訴原始數據內容和更新內容,需要client再次主 ...
  • "minio java client" 使用okhttp作為底層的http實現,在產品包裡面區域網上傳文件的速度一直只有400~800KB/s,經過一天排查發現是 禁用了即時編譯導致。 發現問題的場景 minio java的使用架構圖是這樣的: [Minio Server] ...
  • Python擅長的領域: WEB開發:Django\pyramid\Tornado\Bottle\Flask\WebPy網路編程:Twisted\Requests\Scrapy\Paramiko科學運算:SciPy\Pandas\IpythonGUI圖形開發:wxPythin\PyQT\Kivy運維 ...
  • 1.1 基於UDP協議實現簡單的套接字通信 udp是無鏈接的,先啟動哪一端都不會報錯 udp套接字簡單示例 1.1.1.1 客戶端: from socket import * client=socket(AF_INET,SOCK_DGRAM) #數據報協議,創建一個客戶的套接字 while True ...
  • 在python中,可以使用try...except語句來處理異常。做法是,把可能引發異常的語句放在try 塊中,把處理異常的語句放在except 塊中。 當程式在try內部打開文件引發異常時,會跳過try中剩下的代碼,直接跳轉到except中的語句處理異常。於是輸出了“File not exists ...
  • Python讀寫csv文件 覺得有用的話,歡迎一起討論相互學習~ "Follow Me" 前言 逗號分隔值(Comma Separated Values,CSV,有時也稱為字元分隔值,因為分隔字元也可以不是逗號),其文件以純文本形式存儲表格數據(數字和文本)。純文本意味著該文件是一個字元序列,不含必 ...
  • 前言 在上一篇 "Kafka使用Java實現數據的生產和消費demo" 中介紹如何簡單的使用kafka進行數據傳輸。本篇則重點介紹kafka中的 consumer 消費者的講解。 應用場景 在上一篇kafka的consumer消費者,我們使用的是自動提交offset下標。 但是offset下標自動提 ...
  • Python 學習之路(一) 以下所用的是Python 3.6 一、編碼問題 二、基礎知識 2.1 標識符 在 Python 里,標識符由字母、數字、下劃線組成。 在 Python 中,所有標識符可以包括英文、數字以及下劃線(_),但不能以數字開頭。 Python 中的標識符是區分大小寫的。 2.2 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...