I've made a chat program, only the client is able to send. What I
would like to do is have the client send and receive at the same time.
Same with the server. My source code is probably not the best, but oh
well. I'm programming in Linux-Mandrake 8.0, in C.
----------------------------------------------------------
Server source:
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIZE sizeof(struct sockaddr_in)
int newsockfd;
main()
{
int sockfd;
struct sockaddr_in server = {AF_INET, 7000, INADDR_ANY};
char rmessage[513], smessage[512];
// create socket
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket call failed!");
exit(1);
}
// bind to 7000
if ( bind(sockfd, (struct sockaddr *)&server, SIZE) == -1)
{
perror("bind call failed!");
exit(1);
}
// listen on all available "lines"
if ( listen(sockfd, 5) == -1)
{
perror("listen call failed!");
exit(1);
}
// accept and send/recv data
for ( ; ; )
{
if ( (newsockfd = accept(sockfd, NULL, NULL)) == -1)
{
perror("accept call failed!");
exit(1);
}
// send/recv data
while(recv(newsockfd, &rmessage, 512, 0) > 0)
{
printf("%s\n", rmessage);
} // another while loop for send?
}
-------------------------------------------------------------------Quote:}
client source:
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIZE sizeof(struct sockaddr_in)
main()
{
int sockfd;
struct sockaddr_in server = {AF_INET, 7000};
char servip[64], smessage[1024];
printf("Server IP: ");
gets(servip);
server.sin_addr.s_addr = inet_addr(servip); // server's address
// create socket
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket call failed");
exit(1);
}
// connect to server
if ( connect(sockfd, (struct sockaddr *)&server, SIZE) == -1)
{
perror("connect call failed");
exit(1);
}
else
printf("Connected to: %s\n", servip);
// send/recv data
for( ; ; ) // probably wrong kind of loop?
{
printf("Message: ");
gets(smessage);
send(sockfd, &smessage, 511, 0);
close(sockfd);
} // while loop nested inside the for? another for? while loop
outside of for?
----------------------------------------------------------------Quote:}
as you see, my source may be a little unethical, but it works for me.
Could I please have specific code. Thank you for all your help.