[問題] 用socket的recv()接收中文…
我用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
02/05 14:39, 1F
→
02/05 15:13, , 2F
02/05 15:13, 2F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 4 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章