Geo Paul
Geo Paul

Reputation: 1817

Data not send/received properly

I am trying to implement a TCP server/client using sockets in c. I have written the program in such a way that whatever we send in the client is displayed in the server line by line till exit is typed. The program works but the data is shown in the server all together at the last. Can anybody please check the code?

TCP SERVER

#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

main()
{
    char buf[100];
    socklen_t len;
    int k,sock_desc,temp_sock_desc;
    struct sockaddr_in client,server;

    memset(&client,0,sizeof(client));
    memset(&server,0,sizeof(server));
    sock_desc = socket(AF_INET,SOCK_STREAM,0);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_port = 7777;

    k = bind(sock_desc,(struct sockaddr*)&server,sizeof(server));
    k = listen(sock_desc,20);
    len = sizeof(client);
    temp_sock_desc = accept(sock_desc,(struct sockaddr*)&client,&len);

    while(1)
        {
        k = recv(temp_sock_desc,buf,100,0);
        if(strcmp(buf,"exit")==0)
            break;

        if(k>0)
            printf("%s",buf);
    }

    close(sock_desc);
    close(temp_sock_desc);
    return 0;
}

TCP CLIENT

#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

main()
{
    char buf[100];
    struct sockaddr_in client;
    int sock_desc,k;

    sock_desc = socket(AF_INET,SOCK_STREAM,0);
    memset(&client,0,sizeof(client));
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr("127.0.0.1");
    client.sin_port = 7777;

    k = connect(sock_desc,(struct sockaddr*)&client,sizeof(client));

    while(1)
        {
        gets(buf);
        k = send(sock_desc,buf,100,0);

        if(strcmp(buf,"exit")==0)
            break;
    }

    close(sock_desc);
    return 0;
}

Upvotes: 0

Views: 215

Answers (2)

blaze
blaze

Reputation: 4364

gets() replaces terminating newline with '\0'. Resulting string is sent to server, which writes it to stdout. Stdout is buffered, so nothing will appear on screen until program terminates or '\n' is printed.

Add '\n' to your printf:

if(k>0)
    printf("%s\n",buf);

Upvotes: 1

wildplasser
wildplasser

Reputation: 44250

while(1){
    k = recv(temp_sock_desc,buf,100,0);
    if(memcmp(buf,"exit", 4)==0)
        break;
    if(k>0)
        printf("%*.*s", k, k, buf);
}

The result of recv() is not a string, so it will not be nul-terminated. The above "fix" is not entirely correct, but is only intended to point you in the right direction.

Upvotes: 2

Related Questions