ali73
ali73

Reputation: 415

c++ socket sending data after disconnection

I'm writing a socket code with C++ and socket.h library and my server and clients are stream socket with TCP protocol. I've got a class User that shows the clients connected.

class User
{
 private:
    int sockfd;
    int n;
    thread *Thread;
 public:
    User(int sockfd);
    void Get_Message();
    void Join();  
    ~User();
};
User::User(int sockfd)
{
    this->sockfd=sockfd;
    Thread=new thread(&User::Get_Message,this);
}
void User::Get_Message()
{
    while (1)
    {
        readmessage(sockfd);
    }
}
void readmessage(int sock)
{
    int n=0;
    char buffer[256];
    bzero(buffer, 256);
    n = read(sock, buffer, 255);
    if (n < 0)
    {
        error("ERROR reading from socket ");
    }
    cout<<"the message\t"<<buffer<<endl;
}

now this code works and several clients can join my server and send message;

However when one of those clients disconnects from the server, it keeps printing "the message:" and I don't know why and how to stop it... I'll be grateful if anybody helps me with the why and how to fix it.

Upvotes: 0

Views: 754

Answers (3)

JerryYoung
JerryYoung

Reputation: 277

The read or write function return zero while the other peer disconnected, and the buffer is null, so you should deal with this case.

void readmessage(int sock)
{
    int n=0;
    char buffer[256];
    bzero(buffer, 256);
    n = read(sock, buffer, 255);
    if (n < 0)
    {
        error("ERROR reading from socket ");
    }
    else if (n == 0)
    {
        cout << sock <<" client disconnected" << endl;
    }
    else {
        cout<<"the message\t"<<buffer<<endl;
    }
}

Upvotes: 0

Chrim
Chrim

Reputation: 100

In your Get_Message() while loop, you might need to check if the sockfd is valid , hence sockfd !=0 before reading the message.

Upvotes: 0

user207421
user207421

Reputation: 310860

You aren't checking for read() (or recv()) returning zero, which is the normal case for a disconnected peer.

Upvotes: 2

Related Questions