LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   write() a variable(integer) to socket? (https://www.linuxquestions.org/questions/programming-9/write-a-variable-integer-to-socket-202447/)

koyi 07-08-2004 12:41 AM

write() a variable(integer) to socket?
 
I am working on a server/client chat system.
I want to add a feature to the server so that when the client sends "/list\n" to the server,
the server will send all the names of the users currently logged in, together with the total number of the logged-in users.

So, I send the usernames like this from the server:

Code:

for (j=0; j<k; j++) {
              write(csock[i],user[j],sizeof(user[j]));
              write(csock[i],"\n",1);
            }

where user[j] stores the username.

So, how can I send the number of the logged-in users, k, to the socket so that the client can get it? btw, k is an integer.

Thanks.

shishir 07-08-2004 06:03 AM

simply send an integer cast as a void * and taken out as an int..size of the buffer being 4 or 2 as the case may be, also better to use send instead of write for sockets...

itsme86 07-08-2004 08:56 AM

Another option is to do something like this:

sprintf(buf, "%d\n", k);
write(csock[i], buf, strlen(buf)+1);

koyi 07-08-2004 09:03 AM

Quote:

Originally posted by shishir
also better to use send instead of write for sockets...
Could you please elaborate further on this suggestion?
I have just started learning socket programming at school,
our lecturer used write() instead of send() throughout the given examples.
I am interested to know about the reasons... :p

Thanks :) and of course thanks for showing the way to send variable over sockets :cool:

koyi 07-08-2004 09:07 AM

Quote:

Originally posted by itsme86
sprintf(buf, "%d\n", k);
Wow, an excellent idea of changing integer to string!
Thanks :)

shishir 07-08-2004 09:30 AM

the reason i say send is because send is meant only for sockets and write is mainly for all fd's (incl. sockets), also you are getting a lot of options like out of bound data, etc that means that the other side can read this data as urgent data..etc...MSG_OOB, et al.
this option is the main difference other than the errors returned by the send call when you try a write on a non socket fd..

koyi 07-08-2004 09:42 AM

Thanks guys!
Now my server/client chat system is ready! :D


All times are GMT -5. The time now is 06:48 PM.