1

I want to create a server and client, running on linux such that

  1. Connection is established
  2. Client sends a message to the server
  3. Server sends a response to the client
  4. End connection

Using http://www.thegeekstuff.com/2011/12/c-socket-programming/, this is what I came up with.

TCPSockets.cpp

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <iostream>

int createConnection(char *ipaddr)
{
    int sockfd = 0;
    struct sockaddr_in serv_addr;

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Error : Could not create socket \n");
        return -1;
    }

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(5000);

    if(inet_pton(AF_INET, ipaddr, &serv_addr.sin_addr)<=0)
    {
        printf("\n inet_pton error occured\n");
        return -1;
    }

    if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
       printf("\n Error : Connect Failed \n");
       return -1;
    }

    return sockfd;
}

void receiveMessage(int sockfd)
{
    int n = 0;
    char recvBuff[1024];

    memset(recvBuff, '0',sizeof(recvBuff));

    while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
    {
        std::cout<<"recvBuff="<<recvBuff<<std::endl;
        recvBuff[n] = 0;
        if(fputs(recvBuff, stdout) == EOF)
        {
            printf("\n Error : Fputs error\n");
        }
    }

    if(n < 0)
    {
        printf("\n Read error \n");
    }
}

int createListeningSocket()
{
    int listenfd = 0;
    struct sockaddr_in serv_addr;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(5000);

    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(listenfd, 10);

    return listenfd;
}

void sendMessage(int connfd, char * format) {
    char sendBuff[1025];
    memset(sendBuff, '0', sizeof(sendBuff));

    snprintf(sendBuff, sizeof(sendBuff), format);
    write(connfd, sendBuff, strlen(sendBuff));
}

Server.cpp

#include "TCPSockets.cpp"

int main(int argc, char *argv[]) {
    std::cout<<"Creating socket..."<<std::endl;
    int listeningSocketDescriptor = createListeningSocket();
    std::cout<<"Socket created."<<std::endl;

    std::cout<<"Waiting for connection..."<<std::endl;
    int clientSocketDescriptor = accept(listeningSocketDescriptor, (struct sockaddr*)NULL, NULL);
    std::cout<<"Connection made."<<std::endl;

    std::cout<<"Waiting for message..."<<std::endl;
    receiveMessage(listeningSocketDescriptor);
    std::cout<<"Message received."<<std::endl;

    std::cout<<"Sending message..."<<std::endl;
    sendMessage(clientSocketDescriptor, "From server!");
    std::cout<<"Message sent."<<std::endl;

    std::cout<<"Closing client socket..."<<std::endl;
    close(clientSocketDescriptor);
    std::cout<<"Client socket closed."<<std::endl;

    close(listeningSocketDescriptor);

    return 0;
}

Client.cpp

#include "TCPSockets.cpp"

int main(int argc, char *argv[]) {
    if(argc != 2)
    {
        printf("\n Usage: %s <ip of server> \n",argv[0]);
        return 1;
    }

    std::cout<<"Creating connection..."<<std::endl;
    int socketDescriptor = createConnection(argv[1]);
    if (socketDescriptor < 0)
    {
        return 1;
    }
    std::cout<<"Connection created."<<std::endl;

    std::cout<<"Sending message..."<<std::endl;
    sendMessage(socketDescriptor, "From client!");
    std::cout<<"Message sent."<<std::endl;

    std::cout<<"Waiting for response..."<<std::endl;
    receiveMessage(socketDescriptor);
    std::cout<<"Response received."<<std::endl;

    return 0;
}

Everything works except the server receiving a message. What am I doing wrong?

4
  • It's not clear what you are asking for. If the server is not receiving the request, then nothing is working... but you say Everything works except.... Could you clarify? Commented Apr 7, 2015 at 0:22
  • 1
    You're not checking the return values from bind() or listen(), so if either one of those calls was failing you wouldn't know it. A failure of either one of those calls would prevent your server from accepting connections. Commented Apr 7, 2015 at 0:29
  • And when you do get an error, print the error, not just 'read error' for example. Use perror() or the string returned by strerror(). Commented Apr 7, 2015 at 0:44
  • What is a "message"? Be as precise as possible. I suspect you forgot to define and implement a message protocol and are expecting TCP to be a message protocol by itself. But it's not -- TCP is a byte-stream protocol, not a message protocol. If you want to receive a message, you've got to precisely define what a message is in your message protocol and write code to receive one. It won't happen by magic. Commented Apr 7, 2015 at 0:56

1 Answer 1

1

Your code is:

int clientSocketDescriptor = accept(listeningSocketDescriptor, 
                                              (struct sockaddr*)NULL, NULL);
receiveMessage(listeningSocketDescriptor);

But you should read bytes from a client socket descriptor returned from accept():

int cs = accept(listeningSocketDescriptor, (struct sockaddr*)NULL, NULL);
receiveMessage(cs);

not from the listeningSocketDescriptor.

Sign up to request clarification or add additional context in comments.

8 Comments

Also, your receiveMessage function doesn't make any sense. There is nothing in it anywhere that has anything to do with any kind of message. Where's the code to receive a message?!
@DavidSchwartz Author reads from socket: while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
Right. So where's the logic to decide whether or not he's received a message or find the end of the message? It just keeps reading until there's an error.
At the moment the stop can be caused by closing the socket by the client, this is not an error though, however most likely also not intended behavior
That's not the case. The most obvious indication -- he calls sendMessage and then receiveMessage on the same connection. How would that work if sending a message required closing the connection?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.