Python network programming (i)

Source: Internet
Author: User

Recently gnawing at "Python Core programming (third edition)", it feels that this book is not particularly friendly, although there is an improved code based on Python3, but the whole book of the benchmark feeling is still python2.7. So there are still more errors in Python3 's code, such as the second chapter of network programming:
Original code:

Create a TCP server
#coding=utf-8from socket import *from time import ctimeHOST=''PORT=21567BUFSIZ=1024ADDR=(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 Client
#coding=utf-8from socket import *HOST = 'localhost' #  or 'localhost'PORT = 21567BUFSIZ = 1024ADDR=(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    

If we run in this code, Python3 will quote: Typeerror:a Bytes-like object is required and not ' str ' ERROR. At that time I was very puzzled, python2.7 is clearly applicable, how to Python3 in the "str" it? The reason for the error is that tcpclisock.send (data) passed in the parameter should be the bytes type, not the str type.
The explanation for this is that the rules for encoding and decoding in Python3 and python2.7 are different, see below.

About encoding

(quoted from Liaoche Teacher's tutorial)
Because Python's string type is str, it is represented in memory in Unicode and a character corresponds to several bytes. If you want to transfer on the network, or save to disk, you need to turn str into bytes in bytes.
Python uses single or double quotation marks with a B prefix for data of type bytes: the b‘ABC plain English str can be encoded in ASCII as bytes, the content is the same, and STR with Chinese can be encoded with UTF-8 as bytes. STR, which contains Chinese, cannot be ASCII encoded because the range of Chinese encodings exceeds the ASCII encoding range and Python will error.
In bytes, the bytes that cannot be displayed as ASCII characters are #显示 with \x#.
Conversely, if we read the byte stream from the network or disk, then the data read is bytes. To turn bytes into STR, you need to use the Decode () method.

The modified code
from socket import *from time import ctimeHOST = ''PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT)tcpSerSock = socket(AF_INET, SOCK_STREAM)tcpSerSock.bind(ADDR)tcpSerSock.listen(5)while True:    print('等待连接中')    tcpCliSock, addr = tcpSerSock.accept()    print('...connected from:', addr)    while True:        data = tcpCliSock.recv(BUFSIZ)        if not data:            break        tcpCliSock.send(('[%s] %s' % (ctime(), data)).encode())    tcpCliSock.close()tcpSerSock.close()
from socket import *HOST = '127.0.0.1'PORT = 21567BUFSIZ = 1024ADDR =(HOST, PORT)tcpCliSock = socket(AF_INET, SOCK_STREAM)tcpCliSock.connect(ADDR)while True:    data = input()    if not data:        break    tcpCliSock.send(data.encode())    data = tcpCliSock.recv(BUFSIZ).decode()    if not data:        break    print(data)tcpCliSock.close()

Python network programming (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.