[英]Python sockets: sending UTF-8 with sockets
我正在嘗試將 JSON 文件從服務器發送到客戶端。 問題是,在 JSON 文件中有一個特殊的字符“Ć”,當我在客戶端收到文件時,它寫為“F”。 我不確定我是否必須對其進行解碼/編碼。
這是服務器:
import socket
sourcefile = 'TMS.JSON'
TCP_IP = '10.0.9.6' #IP of server!
TCP_PORT = 3487
s = socket.socket()
s.bind((TCP_IP, TCP_PORT))
s.listen(5)
print('DEBUG: Server listening....')
while True:
conn, addr = s.accept()
print('DEGUG: Got connection from', addr)
f = open(sourcefile, 'rb')
l = f.read(1024)
while (l):
conn.send(l)
l = f.read(1024)
f.close()
print('DEGUG: Done sending')
conn.close()
這是客戶端:
import socket
import json
destinationfile = 'TMS_recieved.JSON'
TCP_IP = '10.0.9.6' #IP of server!
TCP_PORT = 3487
s = socket.socket()
s.connect((TCP_IP, TCP_PORT))
print('DEBUG: Recieving data....')
with open(destinationfile, 'wb') as f: #create JSON FILE
while True:
data = s.recv(1024)
if not data:
break
f.write(data)
f.close()
print('DEBUG: Successfully get the file')
s.close()
print('DEBUG: Connection closed')
with open(destinationfile, 'r') as f: #read JSON FILE
datastore = json.load(f)
print()
print('datastore['name'])
可以請人幫助我嗎? 謝謝
在client.py
替換
with open(destinationfile, 'r') as f:
datastore = json.load(f)
和
with open(destinationfile, 'rb') as f:
datastore = f.read().decode('UTF-8')
datastore = json.loads(datastore)
然后它對我有用,如果 TMS.JSON 是
{"name": "Ć"}
Output:
DEBUG: Recieving data....
DEBUG: Successfully get the file
DEBUG: Connection closed
Ć
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.