Home > Software engineering >  Trying to get started with winsock in C, how to keep connected?
Trying to get started with winsock in C, how to keep connected?

Time:01-17

I'm a beginner and trying to set up a TCP-client for the first time, using winsock. I put together a minimal client using some bits of code I found in examples (see below). It's basically working, i.e. I can receive the server's messages, and sending messages gives the expected results.

However, unless I add a loop which constantly does a receive/send routine (or even just the receive part) the connection is closed immediately after it has been established. Can I do something to keep the connection open and only receive or send something when there is demand for it?

The server is a closed source piece of software, so I have no idea about how it is set up.

#include <winsock2.h>
#include <windows.h>
#include <stdio.h>


int startWinsock(void) {
    WSADATA wsa;
    return WSAStartup(MAKEWORD(2, 2), &wsa);
}

int main(void) {
    long rc;
    SOCKET s;
    SOCKADDR_IN addr;

    printf("Starting Winsock... ");

    rc = startWinsock();

    if (rc != 0) {
        printf("Error: unable to start Winsock, error code: %d\n", rc);
    }
    else {
        printf("done.\n");
    }

    printf("Creating socket... ");

    s = socket(AF_INET, SOCK_STREAM, 0);

    if (s == INVALID_SOCKET) {
        printf("Error: Unable to create socket, error code: %d\n", WSAGetLastError());
    }
    else {
        printf("done.\n");
    }

    memset(&addr, 0, sizeof(SOCKADDR_IN));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(10134);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    rc = connect(s, (SOCKADDR*)&addr, sizeof(SOCKADDR));

    if (rc == SOCKET_ERROR) {
        printf("Connection failed, error code: %d\n", WSAGetLastError());
    }
    else {
        printf("Connected to 127.0.0.1.\n");
    }
    

    //if I add a loop here, which receives and/or sends stuff constantly, the connection stays established


    return 0;
}

CodePudding user response:

Very simple:

  1. Your client tries to connect to the server.
  2. If it succeeds, send a command, and read the response.
  3. Keep receiving and sending until you're "done", then close the socket.

In other words:

  • You have control over when to close the connection - the socket will stay open until you close it.
  • Essentially, you're inventing your own custom network protocol

STRONG SUGGESTION:

Review Beej's Guide to Network Programming

  • Related