无法将值存储在结构中(C套接字编程中的服务器)

时间:2017-04-11 21:49:10

标签: c sockets struct tcp server

我正在尝试在C中创建一个TCP套接字服务器,它存储客户端在结构数组中发送到服务器的数据。好吧,到目前为止,这么好。当我打印结构的值时,只有最后一个值(键)存储在struct数组的所有位置! 这是为什么?提前谢谢!

客户代码:     int main(int argc,char * argv [])     {

int sock;
struct sockaddr_in server;


//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);

char *p;
server.sin_addr.s_addr = inet_addr(argv[1]);
int port = strtol(argv[2], &p, 10);
server.sin_port = htons(port);
server.sin_family = AF_INET;
//Connect to remote server
 if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
    perror("connect failed. Error");
    return 1;
}
write(sock , argv[3] ,strlen(argv[3])+1); //send the 3rd argument(which is the input key)
close(sock);
return 0;
}

服务器代码:     struct key_store     {         char * key;     }商店[1024];

int STORED=0;

void handler(int socket_desc)
{
    int client_sock;
    char client_message[1024];

    client_sock = accept(socket_desc, (struct sockaddr *) NULL, NULL);
    printf("Connection accepted\n");
    while( read(client_sock , client_message , 100) > 0 )
    {
        store[STORED].key=client_message;
        STORED++;
    }
    close(client_sock);
}


int main(int argc , char *argv[])
{   
int socket_desc;
struct sockaddr_in server;

server.sin_port = htons( 8888 );

//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
    printf("Could not create socket");
}
printf("Socket created\n");

//Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;

//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
    //print the error message
    perror("bind failed. Error");
    return 1;
}
printf("bind done\n");

//Listen
listen(socket_desc , 5);

int count =0;
while(count < 3)
{
    handler(socket_desc);
    count++;
}

close(socket_desc);

for (int i=0;i<STORED;i++)
{
    printf("KEY --> %s\n",store[i].key); //print the store keys
}

return 0;
}

输入:

./client 127.0.0.1 8888 123456
./client 127.0.0.1 8888 testkey
./client 127.0.0.1 8888 2017

输出:

./server
Socket created
bind done
Connection accepted
Connection accepted
Connection accepted
KEY --> 2017
KEY --> 2017
KEY --> 2017

1 个答案:

答案 0 :(得分:1)

您正在store中存储指向client_message的指针。下一条消息将覆盖该缓冲区。您必须在存储之前复制该消息

put(strdup(client_message));

你有各种其他问题,但这至少会让你前进