[問題] 用socket的recv()接收中文…

看板Python作者 (Anemos)時間16年前 (2009/02/05 13:18), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串1/4 (看更多)
我用socket和threading試著寫了個server, 可以用telnet連上去,server會把輸入的東西再丟回去。 ex. 用telnet 連上後,輸入asdf,server就會回應"You say:asdf"。 但是在試unicode中文有時候會有錯誤, 如輸入"中文",server正常回應"You say:中文", 但輸入"可"時,server就沒回應了。 奇妙的是,如果用big5終端機就沒這樣的問題… 有人知道這是什麼問題嗎? 原始碼如下: # -*- coding: utf-8 -*- # Echo server program import socket import threading class ClientThread(threading.Thread): def __init__(self,channel,details): self.channel = channel self.details = details threading.Thread.__init__(self) def run(self): print 'Recived connection:', self.details[0] self.channel.send("Hi vistor from: "+self.details[0]+"\n") while 1: recv = self.channel.recv(1024) print("Server get:"+repr(recv)) if recv == '': break self.channel.send("You say:"+repr(recv)+"\n") self.channel.send("You say:"+recv) self.channel.close() print 'Closed connection:', self.details[0] if __name__ == "__main__": host = '' # Symbolic name meaning all available interface port = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) while 1: conn, addr = s.accept() ClientThread(conn,addr).start() -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.137.32.135

02/05 14:39, , 1F
編碼的問題吧? 用utf8編碼送出 接收時解碼試試看
02/05 14:39, 1F

02/05 15:13, , 2F
試過了,用.decode('utf8')遇中文就掛…
02/05 15:13, 2F
文章代碼(AID): #19YdQwXK (Python)
文章代碼(AID): #19YdQwXK (Python)