Python2.7与Python3.4 socket.send

时间:2016-05-12 16:54:52

标签: python sockets

我有以下python套接字客户端。这会向socket服务器发送一条小消息。在Python2.7中,这没有任何缺陷。但是在3.4中我获得了以下Traceback。实施是否改变了?我应该采取什么方法进行调试?

Traceback (most recent call last):
  File "echo-client.py", line 19, in <module>
    sockobj.send(line)
TypeError: 'str' does not support the buffer interface

import sys
from socket import *


_server = 'localhost'
_port = 50007

message = ['Hello network world']

if len(sys.argv) > 1:
    _server = sys.argv[1]
    if len(sys.argv) > 2:
        _port = sys.argv[2]

sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((_server, _port))

for line in message:
    sockobj.send(line)
    data = sockobj.recv(1024)
    print('Client received: {}'.format(data))

sockobj.close()

1 个答案:

答案 0 :(得分:1)

更改

sockobj.send(line)

sockobj.send(line.encode())

在Python 3.x send适用于bytes而不是str。或者我们可以说,Python 3.x正确地(我的观点)不再强迫str -> bytes