文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Win32 socket实例

Win32 socket实例

时间:2010-11-14  来源:escarp

服务器端:  

#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...\n");
    sockClient = accept(ListenSocket, NULL, NULL);
    printf("end accept...\n");
    if(INVALID_SOCKET == sockClient)
    {
        printf("accept failed:%d\n", 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\n", 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...\n", 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\n", 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\n", 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\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    //Listen connection

    if(listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        printf("Error at bind():%d \n", 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...\n");
        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()\n");
    
    //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\n", 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.\n");
        WSACleanup();
        return;
    }
    
    printf("Connected to server.\n");

    
    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\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return;
    }

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

    //receive data

    do{
        iResult = recv(ConnectSocket, recvBuf, _BUFFER_LENGTH_, 0);
        if(iResult > 0)
            printf("Bytes received: %d\n", iResult);
        else if(iResult == 0)
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", 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\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return;
    }

    WSACleanup();
    return;
}

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载