• Win32 socket简单实例


    服务器端:
     

    #pragma comment(lib, "Ws2_32.lib")

    #include <stdio.h>
    #include <WinSock2.h>
    #include <WS2tcpip.h>
    #include <process.h>

    #define _LINK_PORT_ 8088
    #define _BUFFER_LENGTH_ 512
    #define _DEFAULT_PORT_ "12345"

    //接受客户端消息的线程函数

    unsigned __stdcall ThreadRecv(LPVOID param)
    {
        SOCKET ListenSocket = (SOCKET)param;

        SOCKET sockClient = INVALID_SOCKET;
        printf("start accept... ");
        sockClient = accept(ListenSocket, NULL, NULL);
        printf("end accept... ");
        if(INVALID_SOCKET == sockClient)
        {
            printf("accept failed:%d ", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }

        char recvBuf[_BUFFER_LENGTH_] = {0};
        int nRecv = 0;
        while( SOCKET_ERROR != nRecv)
        {
            nRecv = recv(sockClient, recvBuf, _BUFFER_LENGTH_, 0);
            printf("ClinetSocket=%d, received count=%d ", sockClient, nRecv);
            if(SOCKET_ERROR == nRecv)
            {
                //标记当前线程为有信号

                _endthreadex(0);
                printf("recv failed! current thread's state is signaled! error=%d, clientsocket=%d", WSAGetLastError(), sockClient);
            }
        }

        //关闭Socket

        printf("ClientSocket=%d, thread closing... ", sockClient);
        shutdown(sockClient, SD_BOTH);
        closesocket( sockClient );
        return 0;
    }

    int main()
    {
        struct addrinfo *result = NULL,
            *ptr = NULL,
            hints;
        int iResult;

        //Initialize winsocket

        WSADATA wsaData;
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_IP;
        hints.ai_flags = AI_PASSIVE;

        //Resolve the local address and port to be used by the server;

        iResult = getaddrinfo(NULL, _DEFAULT_PORT_, &hints, &result);
        if(iResult != 0)
        {
            printf("getaddrinfo failed: %d ", iResult);
            WSACleanup();
            return 1;
        }

        //Create a SOCKET for the server to listen for client connections

        SOCKET ListenSocket = INVALID_SOCKET;
        ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
        if(INVALID_SOCKET == ListenSocket)
        {
            printf("Error at socket(): %d ", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }

        //Setup the TCP listening socket

        iResult = bind(ListenSocket, result->ai_addr, result->ai_addrlen);
        if(iResult == SOCKET_ERROR)
        {
            printf("bind failed: %d ", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }

        //Listen connection

        if(listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
        {
            printf("Error at bind():%d ", WSAGetLastError());
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }

        while(true)
        {
            SOCKET sockClient = INVALID_SOCKET;

            unsigned threadId;
            HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ThreadRecv,(void*)ListenSocket, 0, &threadId);

            printf("waitting for ClinetSocket to finish... ");
            WaitForSingleObject(hThread, INFINITE);
            CloseHandle(hThread);
        }
        WSACleanup();

        return 0;
    }

    客户端:

    #pragma comment(lib, "Ws2_32.lib")

    #include <stdio.h>
    #include <WinSock2.h>

    #define _BUFFER_LENGTH_ 512
    #define _DEFAULT_PORT_ 12345

    void main(int argc, char* argv[])
    {
        //Initialize Winsocket

        WSADATA wsaData;
        int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if( NO_ERROR != iResult)
            printf("Error at WSAStartup() ");
        
        //Create a SOCKET for connecting to server;

        SOCKET ConnectSocket;
        ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if(ConnectSocket == INVALID_SOCKET)
        {
            printf("Error at socket():%ld ", WSAGetLastError());
            WSACleanup();
            return;
        }

        //-----------------

        //the sockaddr_in structure specifies the address family,

        //IP address, and port of the server to be connected to.

        sockaddr_in clientService;
        clientService.sin_family = AF_INET;
        clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
        clientService.sin_port = htons(_DEFAULT_PORT_);

        //Connect to server

        int connRS = connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
        if( SOCKET_ERROR == connRS )
        {
            printf("Failed to connect. ");
            WSACleanup();
            return;
        }
        
        printf("Connected to server. ");

        
        char* sendBuf = "this's a test";
        char recvBuf[_BUFFER_LENGTH_] = {0};
        //Send an initial buffer

        iResult = send(ConnectSocket, sendBuf, strlen(sendBuf), 0);
        if(iResult == SOCKET_ERROR)
        {
            printf("send failed: %d ", WSAGetLastError());
            closesocket(ConnectSocket);
            WSACleanup();
            return;
        }

        printf("Bytes send:%d ", iResult);

        //receive data

        do{
            iResult = recv(ConnectSocket, recvBuf, _BUFFER_LENGTH_, 0);
            if(iResult > 0)
                printf("Bytes received: %d ", iResult);
            else if(iResult == 0)
                printf("Connection closed ");
            else
                printf("recv failed: %d ", WSAGetLastError());

        }while(iResult > 0);

        //shutdown the connection for sending since no more data will be sent;

        iResult = shutdown(ConnectSocket, SD_SEND);
        if(iResult == SOCKET_ERROR)
        {
            printf("shutdown failed:%d ", WSAGetLastError());
            closesocket(ConnectSocket);
            WSACleanup();
            return;
        }

        WSACleanup();
        return;
    }

    阅读(1607) | 评论(0) | 转发(0) |
    给主人留下些什么吧!~~
    评论热议
  • 相关阅读:
    html实现文件夹的上传和下载
    JQuery & Javascript
    JSP Scripting Element
    JSP Filter
    Oct22 实例测试
    JSP HTML error code
    Implicit Object in JSP
    JSP action elements
    JSP lifecycle
    Eclipse 配置Tomcat
  • 原文地址:https://www.cnblogs.com/black/p/5171964.html
Copyright © 2020-2023  润新知