2013-03-24 57 views
1

背景Python的2 - 3個移植問題

我努力學習Python 3.要快速啓動,我端起我的一個簡單的Python腳本2到Python 3的腳本是一個極其簡單和我陷入了一些問題。

的問題

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

我使用套接字.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' 
+1

「我將在出現時添加更多錯誤」:您應該爲每個特定問題開啓新問題。 – Miles 2013-03-24 02:41:08

回答

0

在python3。*,收到什麼socket發送,是字節。所以,你應該嘗試:

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