Linux network development tutorial 6_ Network programming under window

socket interface has been widely used in modern operating systems

  • The socket programming interface under Windows is almost the same as that in Linux
  • Differences

    • Different return types (handle types)
    • The handle is not a file descriptor, and not all files are connected in Window (therefore, send and recv cannot be used for socket s in windows)

Usage of socket() under Windows

SOCKET s = {0};

s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);  // IPPROTO_TCP explicitly indicates the socket where the TCP protocol is created

if (s == INVALID) {  // Error creating socket, invalid returned_ SOCKET
    ERROR("...");
    return -1;
}

Windows network programming interface

#include <winsock2.h>

Function prototypeFunction description
SOCKET socket(int af, int type, int protocal);Create sockets to prepare for network connections
int connect(SOCKET s, const struct sockaddr *addr, int len);Connect to the remote device at the specified address
int send(SOCKET s, const char *buf, int len, int flags);Send data to remote device
int recv(SOCKET s char *buf, int len, int flags);Receive data from remote device
int closesocket(SOCKET s);Close the connection and destroy the socket
int bind(SOCKET s, const struct sockaddr *addr, int len);Associates the socket with the specified address
int listen(SOCKET s, int backlog);Push the socket into listening state and wait for connection
SOCKET accept(SOCKET s, struct sockaddr *addr, int len);Receive client connections
int shutdown(SOCKET s, int howto);Close the connection and stop sending and receiving
closes And shutdown(Linux The following differences also exist: shoutdown No release socket resources

A few nuances

  • Initialize the system environment through WSAStartup() (called first)
  • socket(), accept() error returned INVALID_SOCKET (not allowed, default to - 1)
  • bind(), listen() error returns SOCKET_ERROR (not allowed, default to - 1)
  • connect(), send(),recv() error returns SOCKET_ERROR (not allowed, default to - 1)
  • Clear the system environment through WSACleanup() (last call)

Special instructions for Windows network programming

  • Set link WS2 in project properties_ 32.lib
  • Define variable WSADATA wd
  • Select the socket version and initialize wsastartup (makeword (2,2), & WD)

    • Multiple socket versions exist in Windows

      • MAKEWORD(1, 2) / / the major version is 1 and the minor version is 2. 0x0201 is returned
      • MAKEWORD(2, 2) / / the major version is 2 and the minor version is 2. 0x0202 is returned

Programming experiment: Windows Network Programming Example

client.c

#include "stdafx.h"
#include <winsock2.h>

int _tmain(int argc, _TCHAR* argv[])
{
    SOCKET sock = 0;  // Note the socket type
    struct sockaddr_in addr = {0};
    int len = 0;
    char buf[128] = {0};
    char input[32] = {0};
    int r = 0;

    WSADATA wd = {0};  // Note the variable definition

    if( WSAStartup(MAKEWORD(2, 2), &wd) != 0 )  // Pay attention to initializing the system environment
    {
        printf("startup error\n");
        return -1;
    }

    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if( sock == INVALID_SOCKET )  // Note the return value type
    {
        printf("socket error\n");
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_port = htons(8888);

    if( connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR )  // Note the return value type
    {
        printf("connect error\n");
        return -1;
    }

    printf("connect success\n");

    while( 1 )
    {
        printf("Input: ");

        scanf("%s", input);

        len = send(sock, input, strlen(input) + 1, 0);

        r = recv(sock, buf, sizeof(buf), 0);

        if( r > 0 )
        {
            printf("Receive: %s\n", buf);
        }
        else
        {
            break;
        }
    }

    closesocket(sock);  // be careful
    
    WSACleanup();  // Pay attention to clearing the system environment

    return 0;
}

server.c

// Server.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <winsock2.h>

int _tmain(int argc, _TCHAR* argv[])
{
    SOCKET server = 0;
    struct sockaddr_in saddr = {0};
    SOCKET client = 0;
    struct sockaddr_in caddr = {0};
    int asize = 0;
    int len = 0;
    char buf[32] = {0};
    int r = 0;

    WSADATA wd = {0};

    if( WSAStartup(MAKEWORD(2, 2), &wd) != 0 )
    {
        printf("startup error\n");
        return -1;
    }

    server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if( server == INVALID_SOCKET )
    {
        printf("server socket error\n");
        return -1;
    }

    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(8888);

    if( bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == SOCKET_ERROR )
    {
        printf("server bind error\n");
        return -1;
    }

    if( listen(server, 1) == SOCKET_ERROR )
    {
        printf("server bind error\n");
        return -1;
    }

    printf("server start success\n");

    while( 1 )
    {
        asize = sizeof(caddr);

        client = accept(server, (struct sockaddr*)&caddr, &asize);

        if( client == INVALID_SOCKET )
        {
            printf("client accept error\n");
            return -1;
        }

        printf("client: %d\n", client);

        do
        {
            r = recv(client, buf, sizeof(buf), 0);

            if( r > 0 )
            {
                printf("Receive: %s\n", buf);

                if( strcmp(buf, "quit") != 0 )
                {
                    len = send(client, buf, r, 0);
                }
                else
                {
                    break;
                }
            }

        } while ( r > 0 );

        closesocket(client);
    }
    
    closesocket(server);

    WSACleanup();

    return 0;
}

Question: is select() unique to Linux?

select() function under Windows

  • The select() function is also provided in Windows, and the parameters are exactly the same as those in Linux
  • For the sake of compatibility, only the first parameter in the function select() has no meaning
#include <winsock2.h>

int select(int nfds, fd_set *readfds,
                     fd_set *writefds,
                     fd_set *excepfds,
                     const struct timeval *timeout);

One nuance: select() in Windows is specifically designed for sockets

  • fd_count is used to record the number of socket s of interest
  • fd_array is used to record the socket handle of interest
typedef struct fd_set {
    u_int fd_count;
    SOCKET fd_array[FD_SETSIZE];
}fd_set;

Use example of select() function in Windows

temps = reads;

timeout.tv_sec = 0;
timeout.tv_usec = 10000;

num = select(0, &temps, 0, 0, &timeout);

if (num > 0) {
    unsigned int i = 0;

    for (i=0; i <reads.fd_fount; ++i) {
        if (FD_ISSET(reads.fd_array[i], &temps)) {
            if (reads.fd_array[i] == server) {
            
            }
            else {
    
            }
        }
    }
}

Programming experiment: multiplexing server in Windows

// Select-Server.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <winsock2.h>

SOCKET server_handler(SOCKET server)
{
    struct sockaddr_in addr = {0};
    int asize = sizeof(addr);

    return accept(server, (struct sockaddr*)&addr, &asize);
}

int client_handler(SOCKET client)
{
    char buf[32] = {0};
    int ret = recv(client, buf, sizeof(buf)-1, 0);

    if( ret > 0 )
    {
        buf[ret] = 0;

        printf("Receive: %s\n", buf);

        if( strcmp(buf, "quit") != 0 )
        {
            ret = send(client, buf, ret, 0);
        }
        else
        {
            ret = -1;
        }
    }

    return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
    SOCKET server = 0;
    struct sockaddr_in saddr = {0};
    // unsigned int max = 0;
    int num = 0;
    fd_set reads = {0};
    fd_set temps = {0};
    struct timeval timeout = {0};

    WSADATA wd = {0};

    if( WSAStartup(MAKEWORD(2, 2), &wd) != 0 )
    {
        printf("startup error\n");
        return -1;
    }


    server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    if( server == INVALID_SOCKET )
    {
        printf("server socket error\n");
        return -1;
    }

    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = htons(8888);

    if( bind(server, (struct sockaddr*)&saddr, sizeof(saddr)) == SOCKET_ERROR )
    {
        printf("server bind error\n");
        return -1;
    }

    if( listen(server, 1) == SOCKET_ERROR )
    {
        printf("server listen error\n");
        return -1;
    }

    printf("server start success\n");

    FD_ZERO(&reads);
    FD_SET(server, &reads);

    // max = server;

    while( 1 )
    {
        temps = reads;

        timeout.tv_sec = 0;
        timeout.tv_usec = 10000;

        // num = select(max+1, &temps, 0, 0, &timeout);
        num = select(0, &temps, 0, 0, &timeout);

        if( num > 0 )
        {
            unsigned int i = 0;

            for(i=0; i<reads.fd_count; i++)  // Compared with the advantages of Linux, you only need to traverse the number of socket handles actually monitored!!
            {
                SOCKET sock = reads.fd_array[i];

                if( FD_ISSET(sock, &temps) )
                {
                    if( sock == server )
                    {
                        SOCKET client = server_handler(sock);

                        if( client != INVALID_SOCKET )
                        {
                            FD_SET(client, &reads);

                            // max = (client > max) ? client : max;

                            printf("accept client: %d\n", client); 
                        }
                    }
                    else
                    {
                        int r = client_handler(sock);

                        if( r == -1 )
                        {
                            FD_CLR(sock, &reads);

                            closesocket(sock);
                        }
                    }
                }
            }
        }
    }
    
    closesocket(server);

    WSACleanup();

    return 0;
}

Thinking: how to write network programs that can be compiled and run across platforms?

Tags: C Linux socket

Posted by iphone2008 on Thu, 28 Apr 2022 05:12:18 +0300