您的位置:首页 > 移动开发 > Objective-C

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

2017-07-29 00:52 1046 查看
# -*- 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python socket
相关文章推荐