C Client/Server Communicating with fprintf?
How would you make a server be able to send messages to a client using printf or fprintf instead of using the write system call?
I already have my server made and working, sending messages via write, but I would rather use fprintf.
For example this didn't work:
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
FILE *fp = fdopen(newsockfd, "w");
fprintf(fp, "test");
fflush(fp)开发者_如何转开发;
I know have a new problem. When I have just the above code it works and I can see it in my browser, however if I add read(newsockfd,buffer,255) after then I on longer see the message posted in my client.
The functions that work on FILE
s are very unlikely to do what you expect them to do when working on sockets, and are more than likely to mess things up for you. If you want to implement formatting, I'd suggest you roll your own formatting functions to write to the sockets: all you need to do is create a variadic function, call vsprintf
to the formatting and send the result over with write
or send
...
How bout using a dup system call, so redirect the stdout to socket descriptor.. so I think you can put your stuff in socket using printf.
精彩评论