Good day everyone,
I'm doing a chat client-server program:server is to receive messages from clients through a TCP port and multicast them back to all clients through a UDP port.
This is my client program. I'd not know why it just sends and receives msg from server once, then it stops.
Is there anything wrong in my code?
Please help me. I'd appreciate it.
Code:
//Program client_distri.c.
//Get and display distributed message
#include <sys/types.h> // for type
#include <sys/socket.h> // for socket API
#include <netinet/in.h> // for address
#include <arpa/inet.h> // for sockaddr_in
#include <stdio.h> // for printf()
#include <stdlib.h> // for atoi()
#include <string.h> // for strlen()
#include <unistd.h> // for close()
////////////////////////////////////////////
char *multiHostAddress = "239.255.10.10";
void getEcho (int sock)
{
struct sockaddr_in read_EP;
int stop = -1;
char *msg;
printf ("Waiting for message... \n");
while (stop < 0)
{
msg = (char *)recvfromDST (&read_EP, sock);
if (msg != NULL)
printf ("%s==>%s\n",inet_ntoa(read_EP.sin_addr),msg);
else
stop = 0;
}
}
////////////////////////////////////////////
int main(int argc, char **argv)
{
int sockMulti;
int readPort;
struct sockaddr_in EP_multi;
struct ip_mreq request;
unsigned char TTL=3;
//-------------
int MC_socket;
struct sockaddr_in server_EP, sender_EP;
char msg [60];
char *readmsg;
int port;
int stop = 0;
//--------------
//--------------
if (argc != 4)
{
IO_error(1,"Need host, send port and receive port.(e.g localhost 9000 9001)");
}
//--------------
else
{
//-----------------------------
//Send msg to server
port = atoi (argv[2]);
printf ("TCP Client to send message to Server %s at Port %d \n", argv[1], port);
setHostByName (&server_EP, argv[1], port);
MC_socket= sockTCP_create();
sock_connect(MC_socket, &server_EP);
while (stop == 0)
{
printf ("Enter message -without space- to send or 'QUIT' \n");
printf ("or 'SerEnd$$' to stop server: ");
//Read msg from user
scanf ("%s", msg);
//Send msg to server
sendtoDST (sender_EP, MC_socket, msg);
printf ("Message %s sent \n", msg);
stop = (strncmp (msg, "QUIT", 4) == 0);
if (stop == 0)
{
stop = (strncmp (msg, "SerEnd$$", 8) == 0);
}
//Receive msg from server
readPort = atoi (argv[3]);
printf ("Multicasting receiver at ports %d \n", readPort);
//Initialisation
sockMulti = sockUDP_create();
sockUDP_reuse (sockMulti);
setHostByAddr (&EP_multi, "any", readPort);
sock_bind (sockMulti, readPort);
sockUDP_join (sockMulti, multiHostAddress,&request);
//Use service
getEcho (sockMulti);
//Finalisation
sockUDP_drop (sockMulti, request);
close(sockMulti);
//----------------------------------
}
sock_shutdown(MC_socket, 1);
readmsg = NULL;
while (readmsg != NULL)
readmsg = (char *)readMessage(MC_socket);
//-----------------------------------
}
}