1

バックグラウンド

私はPython 3を学ぼうとしています.ジャンプスタートするために、私の単純なPython 2スクリプトをPython 3に移植しています.スクリプトは非常に単純で、いくつかの問題で立ち往生しています.

問題

  1. TypeError: 'str' does not support the buffer interface

socket.send()コマンドを使用して、サーバーのウェルカム メッセージを送信します。サーバーが送信しようとすると、上記のエラーが発生します。関連するコードは次のとおりです。

def clientthread(connection):

    #Sending message to connected client
    #This only takes strings (words

    connection.send("Welcome to the server. Type something and hit enter\n")

    #loop so that function does not terminate and the thread does not end
    while True:

        #Receiving from client
        data = connection.recv(1024)
        if not data:
            break
        connection.sendall(data)
        print (data)
    connection.close()

そして、ここにトレースバックがあります:

Unhandled exception in thread started by <function clientthread at 0x1028abd40>
Traceback (most recent call last):
  File "/Users/*****/Desktop/Coding/Python 3/Sockets/IM Project/Server/Server v3.py", line 41, in clientthread
    connection.send("Welcome to the server. Type something and hit enter\n")
TypeError: 'str' does not support the buffer interface

ノート:

Python 2.7.3 から Python 3.3 に移植しています

エラーが発生したら、さらに追加します。


編集

[これ] はすばらしい回答でしたが、問題があるようです。サーバーに送信されるすべてのメッセージの前にb. 私のクライアントは Python 2 です (今夜遅くに移植します) - これは問題の一部でしょうか? いずれにせよ、ここに関連するコードがあります。

クライアントのメイン ループ

while True:   
    #Send some data to the remote server
    message = raw_input(">>>  ")

    try:
         #set the whole string
         s.sendall(USER + " :  " + message)
    except socket.error:
    #Send Failed
        print "Send failed"
        sys.exit()

    reply = s.recv(1024)
    print reply

シェル スタッフ サーバー

HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx :  Hello'
4

2 に答える 2

1

Unicode の Python 3 ガイド(およびPython 2 コードの Python 3 への移植)を確認する必要があります。 send()バイトが必要ですが、文字列を渡しています。encode()送信する前に文字列のメソッドを呼び出し、decode()印刷する前に受信したバイトのメソッドを呼び出す必要があります。

于 2013-03-24T02:39:22.343 に答える
0

python3.* では、どのソケットが送受信するかはバイトです。したがって、次を試してください:

connection.send(b"Welcome to the server. Type something and hit enter\n")
于 2013-03-24T02:39:05.013 に答える