Python -- socket 服务端给客户端发送 json,报错 TypeError: must be string or buffer, not dict

服务端代码:

import socket
import json

msg = {
    "Fans":1,
    "Raid":1,
    "boardTemperature":66,
    "Power":1         
}


socketserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketserver.bind(("10.10.0.1",8888))
socketserver.listen(100)
while True:
    print("waiting connect...")
    clientsocket,addr = socketserver.accept()
    print("client ip:"+addr[0])
    print("client port:"+str(addr[1]))
    recvmsg = clientsocket.recv(1024)
    print("parmRevFromClient:"+recvmsg)
    if recvmsg=='Windows': 
        clientsocket.sendall(msg)
        clientsocket.close()
        print("clientsocket close")

报错发生在 clientsocket.sendall(msg),提示 TypeError: must be string or buffer, not dict

解决:
json.dumps() 函数可以将字典(dict)转化为字符串(string),json.loads() 函数则反过来

修改后:

import socket
import json

msg = {
    "Fans":1,
    "Raid":1,
    "boardTemperature":66,
    "Power":1         
}


socketserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketserver.bind(("10.4.79.55", 8887))
socketserver.listen(100)
while True:
    print("waiting connect...")
    clientsocket,addr = socketserver.accept()
    print("client ip:"+addr[0])
    print("client port:"+str(addr[1]))
    recvmsg = clientsocket.recv(1024)
    print("parmRevFromClient:"+recvmsg)
    if recvmsg=='Windows': 
        sendmsg = json.dumps(msg)  <-- 修改
        clientsocket.sendall(sendmsg)  <-- 修改
        clientsocket.close()
        print("clientsocket close")

你可能感兴趣的:(#,Python)