Perfect for network communication under Windows

Source: Internet
Author: User
Tags socket connect socket error htons

Build Environment: DEV C + + configuration compiler

The implementation of Socket compilation under Windows needs to ws2_32.lib the support of this library, so we should configure the following compiler before compiling, the configuration steps are as follows:

Tools -> Compiler Options

Join the-L Link:

Features implemented

The server side and the client can freely send messages to each other, regardless of the order of receiving and sending (using thread implementation)! You can implement addition operations. If you need other functions, you can add it yourself, such as: realize arithmetic, file transfer and so on.

Server programs
/* NAME:TCP server Copyright:-lws2_32 author:lance# DATE:18/05/18 description:tcp Server */#include &  lt;stdio.h> #include <winsock2.h> #include <windows.h> #include <string.h> #define PORT 8080 #define BUFSIZE 1024/* client SOCKET with send buffer */socket client;unsigned char sendbuf[bufsize+1];enum{noconnection, Conn ected,}linkstatus;/* Client Connection Status monitoring thread */dword WINAPI print_message (LPVOID Arg) {while (1) {if (!            Linkstatus) {printf ("Waiting for client connections .... \ r \ n");        Sleep (1);         The}}/* server sends the message thread */dword WINAPI send_message (LPVOID Arg) {while (1) {memset (sendbuf, 0, 1024);        Fgets (SendBuf, 1024x768, stdin);    Send (client, SENDBUF, 1024, 0);    }} int main (int argc, char* argv[]) {wsadata wsadata;    struct sockaddr_in sin_addr;    struct sockaddr_in remoteaddr;    unsigned char recvdata[bufsize+1];        int naddrlen = sizeof (REMOTEADDR);    unsigned int num_l, num_r; unsigned char sum_buf[100] = {0};        /* Thread ID */HANDLE pthread;    /* Start WSA */WORD sockversion = Makeword (2, 2);        if (WSAStartup (Sockversion, &wsadata)) {perror ("WSA boot failed!");    return-1;    }/* Create a service-side socket */SOCKET SERVER = socket (af_inet, sock_stream, ipproto_tcp);        if (server = = Invalid_socket) {perror ("SOCKET error!");    return-1;    }/* Config SIN_ADDR */sin_addr.sin_family = af_inet;    Sin_addr.sin_port = htons (port); /* Listen to any address */SIN_ADDR.SIN_ADDR. S_un.     S_ADDR = Inaddr_any; /* Listen for the specified address *///sin_addr.sin_addr. S_un.         S_ADDR = inet_addr ("192.168.1.149");         /* bind */if (BIND (server, (LPSOCKADDR) &sin_addr, sizeof (sin_addr)) = = Socket_error) {perror ("bind error!");    return-1;        }/* Monitor */if (listen (server) = = Socket_error) {perror ("Listen error!");    return-1;         } puts ("Server successfully started");    /* Create a status thread */CreateThread (null,0,print_message,null,0,null); /* Create message Thread */PTHRead = CreateThread (null,0,send_message,null,0,null);        while (1) {linkstatus = noconnection;        Client = Accept (server, (SOCKADDR *) &remoteaddr, &naddrlen);                Linkstatus = Connected;            if (client = = Invalid_socket) {perror ("accept error!");        Continue        } printf ("Client:%s is connected \ r \ n", Inet_ntoa (REMOTEADDR.SIN_ADDR));            while (1) {/* Data received */memset (recvdata, 0, sizeof (recvdata));            int ret = recv (client, RecvData, 1024, 0);                if (Ret > 0) {printf ("Recv:%s", recvdata); /* To implement the addition operation, after the client sends the data in the form "%d +%d =", the result is returned to the client */if (sscanf (RecvData, "%d +%d =", &num_l, &num_r) =                    = 2) {sprintf (Sum_buf, "%d +%d, sum is%d", num_l, Num_r, num_l + num_r);                    Send (client, sum_buf, sizeof (SUM_BUF), 0);                memset (sum_buf, 0, sizeof (SUM_BUF));        }    }else/* Client exception disconnects the current connection */goto reconnect;        /* Disconnect the current connection if the client requires exit */if (!strncmp (RecvData, "Quit", 4)) Goto reconnect;        } reconnect:closesocket (client);    Puts ("* * * client disconnected");     }/* Close the server socket */closesocket (server);        WSACleanup (); return 0;}
Client programs
/* name:tcp Client Copyright:-lws2_32 author:lance# date:18/05/18 description:tcp client*/#include &l t;stdio.h> #include <winsock2.h> #include <Windows.h> #include <string.h> #define PORT 808  0 #define BUFSIZE 1024unsigned char recvdata[bufsize+1] = {0};        /* thread ID */handle pthread;dword WINAPI recv_message (LPVOID arg) {int res;         while (1) {memset (recvdata, 0, 1024);        res = recv (SOCKET) arg, RecvData, 1024, 0);        if (res > 0) printf ("Recv:%s", recvdata);            else{printf ("* * * Server has exited (enter exit program)");        return 0;      }}} int main (int argc, char * argv[]) {unsigned char sendbuf[bufsize+1] = {0};    Wsadata Wsadata;          Sockaddr_in Addrserv;        if (argc! = 2) {puts ("ARGC error");        Puts ("Usage: <client.exe> <ip addr>");    return-1;    }/* Start WSA */WORD sockversion = Makeword (2, 2); if (WSAStartup (Sockversion, &Wsadata)) {perror ("WSA boot failed!");    return-1;      }/* Create SOCKET */SOCKET client = socket (af_inet, sock_stream, ipproto_tcp);          if (client = = Invalid_socket) {perror ("SOCKET failed");      return-1;      }/* Config socket */addrserv.sin_family = af_inet;      Addrserv.sin_port = htons (port); /* Configure the server IP */addrserv.sin_addr. S_un.            S_ADDR = inet_addr (argv[1]);    /* Connect to Server */INT ret = connect (client, (sockaddr*) &addrserv,sizeof (sockaddr));          if (socket_error = = ret) {perror ("SOCKET connect Failed");          Closesocket (client);          WSACleanup ();      return-1;        }/* Create worker thread */pthread = CreateThread (null,0, Recv_message, (LPVOID) client,0,null);         Puts ("Client successfully started, enter ' quit ' to close the client");                  while (1) {memset (sendbuf,0,sizeof (SENDBUF));                Fgets (SendBuf, 1024x768, stdin);          RET = Send (client, SENDBUF, 1024, 0);  if (socket_error = = ret) {            Closesocket (client);        Exit (0);    }/* Client exits */if (!strncmp (SendBuf, "Quit", 4)) goto Disconnect;      }disconnect:closesocket (client);          WSACleanup ();  return 0;   }
Run Results Demo

Open CMD and go to the directory where the executable file is located

Execute Server.exe running server;
Start another CMD, execute client.exe 127.0.0.1 run the client.

The two sides can communicate, the effect

Perfect for network communication under Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.