Wojtek
Wojtek

Reputation: 2524

Console based chat. How to separate the messages and the input?

I have to write a simple chat in C. One program is a server to which clients connect and it manages the messages they send. Client is another program and here I've got a problem. I'd like to be able to receive messages from other clients (through the server) and print them on the console output. Yet at the same time I'd like to be able to write my own message and send it to the server (and therefore to other clients).
Problem is, when I write some message, meanwhile receive one from the server, the whole input is messed up. I'd like to somehow separate the message-output area and message-input area. Is there any good way to do that? This is my fork in the client program (still a draft):

int pid = fork();
if(pid==0){
    do{
        scanf("%s", msg);
        printf("sending the message to the server\n");
    } while(strcmp(msg, "exit"));
    kill(getppid(), SIGKILL);
    printf("kill the child\n");
} else {
    while(1){
        printf("receiving a new message\n");
        sleep(1);
    }
}

EDIT:
Ok, I've made a simple ncurses application, but there's one more issue. How could I write to the same window in ncurses when I have two processes (after fork())? They seem to have their separate windows and either I can provide input or read output from the server, but not both on one screen. Any proposals? I didn't want to make IPC between them, only between clients and the server.

EDIT2:
I finally gave up the idea of ncurses due to the approaching deadline. If the program was multithreaded (not multi-processed), then it would work perfectly, but with fork it all became a mess. Anyway, I made my final project in ncurses, so still a useful suggestion :)

Upvotes: 1

Views: 3315

Answers (1)

larsks
larsks

Reputation: 311516

You don't mention whether you're on Windows or Linux...this answers assumes Linux, for the most part.

A typical solution is to use something like ncurses to separate the screen into two "windows", then display messages received from other clients in one window and your input in another window. Curses is a library for taking advantage of terminal control codes for cursor positioning and so forth to provide a simple console-based GUI.

If you've ever used an irc client, you've already experienced something like what I'm describing.

There's a ncurses programming HOWTO, which might be a good place to start.

Upvotes: 2

Related Questions