Friday, 15 August 2014

c - Need Clarification in the socket server while loop -



c - Need Clarification in the socket server while loop -

below part of code socket server. not clear steps have questions. questions below:

why need utilize while (1)? what purpose of exit (-1), close socket? why data_len initialized 1? if server runs , there no info client side, happen server? closed?

actually, need detail explanation below part of code.

while(1) { if ((new = accept(sock, (struct sockaddr*)&client, &sockaddr_len)) == error) { perror ("accept"); exit (-1); } printf("new client connected port no %d , ip %s\n",ntohs(client.sin_port), inet_ntoa(client.sin_addr)); data_len = 1; while (data_len) { data_len = recv (new, data, max_data, 0); if (data_len) { send (new, data, data_len, 0); info [data_len]='\0'; printf("sent mesg: %s", data); } } printf("client disconnected\n"); close(new); } close (sock);

if want take new connections after you're done first one, need same code on 1 time again take , handle new connection. easiest way using loop of kind.

the exit function exits process. typically close open sockets release other open/allocated resources. function not return.

if don't initialize data_len variable, value indeterminate , using lead undefined behavior. @ to the lowest degree if variable local non-static variable.

if there no info client, recv phone call block indefinitely.

c sockets serversocket socketserver localserversocket

No comments:

Post a Comment