how to create multiple tcp connections between server and client

Posted by lowcosthighperformance on Stack Overflow See other posts from Stack Overflow or by lowcosthighperformance
Published on 2012-10-16T22:22:33Z Indexed on 2012/10/17 5:02 UTC
Read the original article Hit count: 140

Filed under:
|
|
|

I am new in Unix/Linux networking programming, so I have written server-client program in below.In this code there is one socket between client and server, client requests to server, then server responses from 1 to 100 numbers to client. So my question is how can we do this process with 3 socket( tcp connection) without using thread? ( e.g. First socket runs then second runs then third runs then first again .. ) Do you have any suggestion? Thank you

client.c

int main()
{

int sock;
struct sockaddr_in sa;
int ret;
char buf[1024];
int x;

sock = socket (AF_INET, SOCK_STREAM, 0);

bzero (&sa, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(SERVER_PORT);
inet_pton (AF_INET, SERVER_IP, &sa.sin_addr);

ret = connect (sock,
(const struct sockaddr *) &sa,sizeof (sa));

if (ret != 0) {
    printf ("connect failed\n");
    exit (0);
}

x = 0;
while (x != -1) {
    read (sock, buf , sizeof(int));
    x = ntohl(*((int *)buf));
    if (x != -1)
    printf ("int rcvd = %d\n", x);
}

close (sock);

exit (0);

}

server.c

int main()
{

int list_sock;
int conn_sock;
struct sockaddr_in sa, ca;
socklen_t ca_len;
char buf[1024];
int i;
char ipaddrstr[IPSTRLEN];

list_sock = socket (AF_INET, SOCK_STREAM, 0);

bzero (&sa, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(SERVER_PORT);
bind (list_sock,(struct sockaddr *) &sa,sizeof(sa));

listen (list_sock, 5);

while (1){

    bzero (&ca, sizeof(ca));
    ca_len = sizeof(ca); // important to initialize
    conn_sock = accept (list_sock,(struct sockaddr *) &ca,&ca_len);

    printf ("connection from: ip=%s port=%d \n",inet_ntop(AF_INET, &(ca.sin_addr),
        ipaddrstr, IPSTRLEN),ntohs(ca.sin_port));

    for (i=0; i<100; ++i){

        *((int *)buf) = htonl(i+20);
        // we using converting to network byte order

        write (conn_sock, buf, sizeof(int));

    }

    * ((int *)buf) = htonl(-1);
    write (conn_sock, buf, sizeof(int));

    close (conn_sock);

    printf ("server closed connection to client\n");

}
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about linux