首页 > 解决方案 > json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)套接字 python

问题描述

我正在尝试制作一个需要两个客户端和一个服务器的小程序。基本上我想将 JSON 从客户端 1 发送到客户端 2(客户端 1 已从服务器接收到),但它不起作用。但是,从客户端 1 到服务器确实可以工作。我使用新的套接字连接从客户端 1 发送到客户端 2(这对于我的分配是强制性的)。我收到这些错误:

File "C:\Users\duser\OneDrive\Bureaublad\clientt.py", line 105, in <module>
    client2()
  File "C:\Users\duser\OneDrive\Bureaublad\clientt.py", line 75, in client2
    newdict = json.loads(receiveclient1)
  File "C:\Users\duser\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\duser\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\duser\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是代码:

import socket
import json
import sys

i = 0

host = "xxx.xx.xxx.xxx"
port = 55550
port2 = 44445
obj = socket.socket()
s = socket.socket()

hostname = socket.gethostname()
complete_info = ''

clientinfo = {"studentnr1": "0982130",
              "studentnr2": "0943260",
              "classname": "INF",
              "clientid": 1,
              "teamname":"Team",
              "ip":socket.gethostbyname(hostname),
              "secret": "",
              "status": ""}


def client1():
    global complete_info, newdict
    obj.connect((host,port))
    while True:
        data = obj.recv(1024)
        if len(data) == 0:
            break
        complete_info = data.decode("utf-8")
        print(complete_info)
        
        clientinfosend = str.encode(json.dumps(clientinfo))
        obj.sendall(clientinfosend)
        inforeceive = obj.recv(1024).decode("utf-8")
        inforeceived = json.loads(inforeceive)
        print(inforeceived)
    
    s.connect((socket.gethostbyname(hostname),port2))
    s.sendall(str.encode(json.dumps(inforeceived)))
    obj.close()
    print("Connection closed")
       

def client2():
    #while loop which listens to connection from client 1
    s.bind((socket.gethostbyname(hostname), port2))
    s.listen()
    conn, addr = s.accept()
    print("Listening for connections")
    while True:
        print('Connection from', addr)
        data = conn.recv(1024).decode("utf-8")
        if not data:
            break

    receiveclient1 = conn.recv(1024).decode("utf-8")
    
    newdict = json.loads(receiveclient1)
    print(newdict)
    temp = newdict["studentnr1"]
    newdict["studentnr1"] = newdict["studentnr2"]
    newdict["studentnr2"] = temp
    newdict["clientid"] = sys.argv[1]
    
    s.close()


num_arguments = len(sys.argv[1:])
i = 1
args = sys.argv[1:]

if int(sys.argv[i]) == 1:
    client1()

elif int(sys.argv[i]) == 2:
    client2()

标签: pythonjsonpython-3.xsockets

解决方案


在 client2 中,您首先读取套接字,直到它被关闭或关闭:

while True:
    print('Connection from', addr)
    data = conn.recv(1024).decode("utf-8")
    if not data:
        break

这意味着当您退出该循环时,不会有任何数据来自套接字。

所以在下一行:

receiveclient1 = conn.recv(1024).decode("utf-8")
newdict = json.loads(receiveclient1)

receiveclient1是一个空字符串,它解释了错误。

您应该改为receiveclient1data片段构建:

receiveclient1 = ''
while True:
    print('Connection from', addr)
    data = conn.recv(1024).decode("utf-8")
    if not data:
        break
    receiveclient1 += data

newdict = json.loads(receiveclient1)

推荐阅读