Hassan Yousuf
Hassan Yousuf

Reputation: 731

C++ Sockets - Sending messages with new line (linux)

I am trying to send messages from client to server and vice versa. The messages are receiving correctly but I have to put an * at the end of every message.

The control loop I am using is *buffer != '*'. I tried to replace with \n or checking with via ASCII value which is 10 through static_cast but the message is not going.

How do I transfer messages when the user enters a new line (\n). I am thinking of cin.getline. is it okay to use it with a pointer?

server.cpp

     do {
            recv(server, buffer, bufsize, 0);
            cout << buffer << " ";
            if (*buffer == '#') {
                *buffer = '*';
                isExit = true;
            }
        } while (*buffer != '*');

        do {
            cout << "\nServer: ";
            do {
                cin >> buffer;
                send(server, buffer, bufsize, 0);
                if (*buffer == '#') {
                    send(server, buffer, bufsize, 0);
                    *buffer = '*';
                    isExit = true;
                }
            } while (*buffer != '*');

            cout << "Client: ";
            do {
                recv(server, buffer, bufsize, 0);
                cout << buffer << " ";
                if (*buffer == '#') {
                    *buffer == '*';
                    isExit = true;
                }
            } while (*buffer != '*');
        } while (!isExit);

client.cpp

     do {
        cout << "Client: ";
        do {
            cin >> buffer;
            send(client, buffer, bufsize, 0);
            if (*buffer == '#') {
                send(client, buffer, bufsize, 0);
                *buffer = '*';
                isExit = true;
            }
        } while (*buffer != 42);

        cout << "Server: ";
        do {
            recv(client, buffer, bufsize, 0);
            cout << buffer << " ";
            if (*buffer == '#') {
                *buffer = '*';
                isExit = true;
            }

        } while (*buffer != 42);

Thanks!

Upvotes: 0

Views: 1068

Answers (1)

user207421
user207421

Reputation: 310980

You're only examining the first character of the buffer. You need to either read one byte at a time (yuck) or scan the entire buffer for the delimiter.

Note that it might be in the middle, before part or all of another message.

Upvotes: 1

Related Questions