服务器无法解码c字符串

时间:2015-11-04 22:04:34

标签: python c sockets encoding utf-8

我在基本的计算机网络上有python和c之间的另一种兼容性。

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()

我的服务器应该从客户端收到一个字符串然后打印它,这只是我检查错误的简单方法。

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;
}

客户端连接,我读取字符串,一切正常,但我的服务器给了我以下错误:

  

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

     

UnicodeDecodeError:'utf-8'编解码器无法解码位置的字节0x80   3:无效的起始字节

提到我尝试了一堆编码进行解码,似乎没什么用。

除了逐个发送字符外,还有什么方法可以使它工作吗?你可以指导我的任何信息都会有所帮助。

1 个答案:

答案 0 :(得分:1)

您发送的数据过多。这一行:

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

发送整个message缓冲区。那不是你想要的。

相反,试试这个:

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