Uifalean Sergiu Mihai
Uifalean Sergiu Mihai

Reputation: 60

Server can't decode c string

i have yet another compatibility between python and c at basic computer networks.

server.py

import socket
import threading
threads=[]
global c
c=0
def client_thread(client_socket):
    global c
    count=c
    try:
        message=client_socket.recv(1010)
        
    except socket.error as error:
        print('error t recv:',error)
        exit(1)
    print('Client #',count,' sent:',message.decode('utf-8'))
    c=c-1
    client_socket.close()
def main():
    server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        server.bind((str(socket.INADDR_ANY),1234))
    except socket.error as error:
        print('binding error:',error)
        exit(1)
    server.listen(5)
    print('Server running')
    while(1):
        client_socket, _ =server.accept()
        print('Client connected.')
        th= threading.Thread(target=client_thread,args=(client_socket,))
        threads.append(th)
        global c
        c=c+1
        th.start()
if __name__ == '__main__':
    main()

My server should receive a string from the client and then print it,it's just a simplified way for me to check the error.

client.c

#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char* argv[]){
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket < 0){
        perror("Error at creating socket\n");
        exit(1);
    }
    struct sockaddr_in server_address;
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_port= ntohs(1234);
    server_address.sin_family=AF_INET;
    server_address.sin_addr.s_addr= inet_addr("127.0.0.1");
    if (connect(client_socket, (struct sockaddr*) &server_address, sizeof(server_address)) < 0){
        perror("Can not connect to server\n");
        exit(1);
    }
    printf("Give String:");
    char message[1000];
    
    scanf("%s",message);
    send(client_socket, message, strlen(message), 0);
    return 0;
}

The client connects,i read the string,everything ok,but my server gives me the following error:

print('Client #',count,' sent:',message.decode('utf-8'))

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3: invalid start byte

Mentioning that i tried a bunch of encoding for the decode,nothing seems to work.

Is there any way to make it work other than sending the characters one by one?Any information you can direct me to would be helpful.

Upvotes: 1

Views: 157

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

You are sending too much data. This line:

send(client_socket, &message, sizeof(message), 0);

sends the entire message buffer. That's not what you want.

Instead, try this:

send(client_socket, message, strlen(message), 0);

Upvotes: 1

Related Questions