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

# -*- coding: utf-8 -*-
'''
Created on 2017年7月28日
@author inx
实现中基本socket程序
'''
import socket 
host = '192.168.0.1'
port = 50010
s = 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 = 50010
s = 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()
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

crystalnsd

万水千山总是情,支持一下行不行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值