python socket send 函数 报错:TypeError: a bytes-like object is required, not 'str'

来源:互联网 发布:监控用网络光端机 编辑:程序博客网 时间:2024/06/06 00:50
# -*- coding: utf-8 -*-'''Created on 2017年7月28日@author inx实现中基本socket程序'''import socket host = '192.168.0.1'port = 50010s = socket.socket()s.connect((host,port))while True:    meg = input('>>>')    if not meg:        break    s.send(meg)    data = s.recv(4096)    print(data)s.close()

报错代码:s.send(meg)
python 3.5 不能直接的传入字符串需要传入bytes-like 对象 ,需要对你使用字符串encode()方法
官方文档描述:

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

正确代码 :

# -*- coding: utf-8 -*-'''Created on 2017年7月28日@author inx实现中基本socket程序'''import socket host = '192.168.0.1'port = 50010s = socket.socket()s.connect((host,port))while True:    meg = input('>>>')    if not meg:        break    s.send(meg.encode(encoding='utf_8', errors='strict'))    data = s.recv(4096).decode(encoding='utf_8', errors='strict')    print(data)s.close()
阅读全文
1 0