Hi to everyone!
I want to create a simple chat application using udp sockets. I want to have 2 applications that will be able to talk to each other.In particular app1 will send msgs to p2 and p2 will display them in stdout. Then maybe p2 sends a msg to p1... etc..
for the initialization part i have the following:
-->> server part initialization.
if (argc != 4)
err_quit("usage: udpcli <IPaddress> <his-Port> <mine-Port>\n");
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
memset( &servaddr, 0, sizeof(servaddr) );
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(atoi( argv[3]) );
//servaddr.sin_port = htons( SERVER_PORT );
Bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr) );
printf("Peer-Server initiated...listening in %s and port %d\n\t waiting for clients\n",
argv[1], ntohs(servaddr.sin_port));
-->> client part initialization
memset( &hisaddr, 0, sizeof(hisaddr) );
hisaddr.sin_family = AF_INET;
hisaddr.sin_port = htons( atoi(argv[3]) );
Inet_pton( AF_INET, argv[1], &hisaddr.sin_addr);
-->> fork so that the application will be able to send and receive messages.
if((childpid = fork()) == 0)
{
//send message to peer
peer_dg_send(stdin, sockfd, (struct sockaddr *) &hisaddr, sizeof(hisaddr));
}
else
{
//receive message from peer
peer_dg_receive(sockfd, (struct sockaddr *) &hisaddr, sizeof(hisaddr) );
}
here are some extra functions:
void peer_dg_receive(int sockfd, struct sockaddr * pcliaddr, socklen_t clilen)
{
int n;
socklen_t len;
char mesg[MAXLINE];
for(;;)
{
len = clilen;
n = Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);
mesg[n] = 0; /* null terminate */
//Fputs(mesg, stdout);
printf("Received: %s", mesg);
}
}
void peer_dg_send(FILE *fp, int sockfd, struct sockaddr *pservaddr, socklen_t servlen)
{
int n;
char sendline[MAXLINE];
while (Fgets(sendline, MAXLINE, fp) != NULL)
{
Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);
}
}
also the functions with the first letter capitalized are from stevens's "unix network programming".
I have to questions in the above scheme:
First, is this the "best" way to tackle the chat problem? or am i missing something in the big picture
Second, it fails to work in the following sense:
each time i try to send something from app1 to app2.
app2 never receives the msg... but instead app1 does! why? and how can i fix it...
any ideas {even if not complete} are welcome!
thanks for your help,
nicolas