KostasRim
KostasRim

Reputation: 2053

linux socket client/server program

Hello my server program is :

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
    int sfd, cfd;
    int ch='k';
    struct sockaddr_in saddr, caddr;

    sfd= socket(AF_INET, SOCK_STREAM, 0);
    saddr.sin_family=AF_INET;           /* Set Address Family to Internet */
    saddr.sin_addr.s_addr=htonl(INADDR_ANY);    /* Any Internet address */
    saddr.sin_port=htons(29008);            /* Set server port to 29008 */
                        /* select any arbitrary Port >1024                */
    bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr));
    listen(sfd, 1);
    while(1) {
            printf("Server waiting...");
            cfd=accept(sfd, (struct sockaddr *)NULL, NULL);
            if(read(cfd, &ch, 1)<0) perror("read");
            ch++;
            if(write(cfd, &ch, 1)<0) perror("write");
            close(cfd);
    }
}

so i got a simple server program and i also got a client program. The problem i have is that when i run both at the same machine on different terminals the client output works fine. The server although doesnt print the waiting line and also it stacks making me unable to use terminal. Whats the problem ?

Upvotes: 1

Views: 1490

Answers (1)

jfly
jfly

Reputation: 7990

As the comment points out, you need send a new line or fflush(stdout) to make the server print what you want, or disable buffering entirely before operating on stdout: setbuf(stdout, NULL), which is not necessary. By default, stdout is line buffered, stderr is none buffered. And note that Microsoft runtime libraries do not support line buffering, so if you implement this program with Winsock, it will print immediately.
Before bind(), you can set the SO_REUSEADDR option so that when your program exits uncleanly(in the code above, you didn't close the listening socket sfd explicitly, though the OS will clean up upon termination, but it's a good practice to do so), the port which may remain in TIME_WAIT state can be re-used immediately.

int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) 

If you want to use the current terminal after you run the program, add a & after your command, so the program will run in the background.

Upvotes: 2

Related Questions