how to build a chat server in c

C

c_eagle

i am building a chat server in c using sockets.i have used fork to do
non-blocking read and write between the client and the server.but i
dont know how to accept multiple clients and relay messages between two
hosts through the server.should i use select()? i have given below the
client program.the server program is almost same except the usual
bind() , listen() calls.if someone has got such a chat program,then
please send the sourcecode.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORT 3468 // the port client will be connecting to
#define MAXDATASIZE 256 // max number of bytes we can get at once

int main(int argc, char *argv[])
{
int sockfd, i,byt=0,pid;
char buf[MAXDATASIZE];
//struct hostent *he;
struct sockaddr_in their_addr; // connector's address information
/* if (argc != 3)
{
fprintf(stderr,"usage: client hostname\n");
exit(1);
}*/
/* if ((he=gethostbyname(argv[1])) == NULL)
{ // get the host info
herror("gethostbyname");
exit(1);
}*/
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
memset( (char*) &their_addr, 0, sizeof(their_addr) ); // zero the rest
of the struct
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(PORT); // short, network byte order
if(inet_pton(AF_INET,argv[1],&their_addr.sin_addr)<=0)
perror("Error in argument");
// their_addr.sin_addr = *((struct in_addr *)he->h_addr);
if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct
sockaddr)) == -1)
{
perror("connect");
exit(1);
}
pid=fork();
if(pid==0)
{
while(1)
{
fgets(buf,255,stdin);
write(sockfd,buf,strlen(buf));
}
}
else if(pid>0)
{
while(1)
{
byt=read(sockfd,buf,255);
if(byt<=0)break;
printf("%s",buf);
}
}

close(sockfd);
return 0;
}

bye.June
 
K

Keith Thompson

i am building a chat server in c using sockets.i have used fork to do
non-blocking read and write between the client and the server.but i
dont know how to accept multiple clients and relay messages between two
hosts through the server.
[snip]

Standard C doesn't support sockets or fork(). Try a newsgroup
specific to your system, perhaps comp.unix.programmer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top