Why I get this error in the json in the server?

53 views Asked by At

I'm working on a project that involves connecting a client in C# with a server in C++. However, I'm encountering an error with the JSON that I pass from the client. Interestingly, I wrote a client in Python that works fine, so I'm struggling to understand what the problem is.

Here's the code I wrote in C#:

This function converts a request to JSON:

public static Packet Serialize(LoginRequest request)
{
    // Serialize request to a JSON string
    string json_data = JsonConvert.SerializeObject(request, Formatting.Indented);
    return new Packet(LOGIN_CODE, json_data);
}

This function sends the packet:

     public void SendPacket(Packet packet)
        {
            // Convert data to bytes
            byte[] byteData = System.Text.Encoding.ASCII.GetBytes(packet.GetData());
            byte[] code = new byte[1] { packet.GetCode() };

            // send the code
            socket.Send(code);

            // send the length
            socket.Send(BitConverter.GetBytes(byteData.Length));

            // send the json data
            socket.Send(byteData);

            MessageBox.Show("Client Sent Data {" + code + "}:");
            MessageBox.Show(packet.GetData());
        }

And this is the error I'm getting: received JSON: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal Client disconnected unexpectedly!

Here's the Python client code (that works fine):

import socket
import struct
import json

# Host and port of the server to connect to
host = "localhost"
port = 8826

# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


def send_message(code, data):
    # Calculate message size
    size = len(data)

    # Send code and message size
    client_socket.send(struct.pack('B', code))
    client_socket.send(struct.pack('!I', size))

    # Send the JSON message
    client_socket.send(data.encode())
    print(f"Sent message: {data} with length {size}")


def receive_message():
    # Receive code
    code = struct.unpack('B', client_socket.recv(1))[0]

    # Receive message size
    size = struct.unpack('!I', client_socket.recv(4))[0]

    # Receive the JSON message
    json_data = client_socket.recv(size + 1).decode()

    # Convert JSON to Python object
    # data = json.loads(json_data)
    print(f"Received response of size {size} with code {code}:")
    print(json_data)


def main():
    # Connect to the server
    client_socket.connect((host, port))
    print("Connected to server")

    # Example messages
    login_message = '{"username": "maya", "password": "1234"}'

    send_message(1, login_message)
    receive_message()

    # Close the socket
    client_socket.close()


if __name__ == "__main__":
    main()
0

There are 0 answers