Hey all!
So my buddies and I have been in the OS programming class and we've gotten ourselves an idea. We get free range to the Unix server for academic purposes and we thought it might be fun to try and write a PTC server so we can chat across our respective sessions within the system rather than using AIM. I know this might be a little bit ahead of where we are in the class so I am most likely out of my depth but I thought it would be fun to try.

Our thought was to create it like a mailer system where any person types in and the message goes to all the others logged on. The server code itself would create the TCP socket and bind the port number to it while creating a finite number of threads(that way if 4 of us wanted to chat we could say create 4 threads and then other people wouldn't be able to jump on AND we wouldn't hog system resources).

The chat client on each person's end would be two threaded so one thread could read from stin and another thread would write to stdout.

Sooo in light of all that here's what I've coded so far. I'm not sure it's right but it seems to compile lol!

#include <pthread.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include	<time.h>
#define SA      struct sockaddr

void            exit();
void           *EchoToClient(void *);

    int             len, listenfd, connfd;
    struct sockaddr_in servaddr, cliaddr;
    char            buff[512];
    int             nread;
    pthread_t       tid;
    pthread_attr_t  attr;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(10123);

    bind(listenfd, (SA *) & servaddr, sizeof(servaddr));

    listen(listenfd, 0);


    for (;;) {
       len = sizeof(cliaddr);
       connfd = accept(listenfd, (SA *) & cliaddr, &len); 
       pthread_create(&tid, &attr, &EchoToClient, (void *) connfd); 

void  *
EchoToClient(void *sockfd)
    int             nread;
    char            buffer[512];
    for (;;) {
       nread = read((int) sockfd, buffer, 512);
       if (nread == 0)
           pthread_exit(0); /* exit(0) */
       write((int) sockfd, buffer, nread);

Basically what happens is one person sets up the server via %EchoServerThread and then the others dial in by %EchoClientFork localhost 10123 but as near as I can tell all I've been able to do is get the server to spit it back at me not other people.

Please bear in mind that since I'm a little out of my depth on this I've kind of cobbled together some stuff I've found around the net and the middle of the code I actually reused from our last assignment with sockets and child processes so I could have definitely fouled it up lol

Thanks for reading and me and my buddies appreciate the help!


This article has been dead for over six months. Start a new discussion instead.