C++ Socket服务器简单代码示例

C++ Socket服务器简单代码示例

#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")

//服务器端
void main()
{   
    WSADATA wsaData;    
    int errorCode = WSAStartup(MAKEWORD(1,1),&wsaData);
    if (errorCode != 0)
        return;


    SOCKET acceptSocket = socket(AF_INET,SOCK_STREAM,0); 

    SOCKADDR_IN addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(6001);        //端口号

    errorCode = bind(acceptSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));   
    if (errorCode != 0)
        return;

    errorCode = listen(acceptSocket,5);
    if (errorCode != 0)
        return;

    SOCKADDR_IN sockAddr;
    int len = sizeof(SOCKADDR);

    char recvBuf[5000] = {0};
    char sendBuf[5000] = {0};
    while (true)
    {
        SOCKET clientSocket = accept(acceptSocket,(SOCKADDR*)&sockAddr,&len);
        if (clientSocket == INVALID_SOCKET)
        {
            Sleep(100);
            continue;
        }

        memset(sendBuf,0,5000);
        sprintf(sendBuf,"%s is Connected!\r\n",inet_ntoa(sockAddr.sin_addr));
        printf(sendBuf);

        while(true)
        {
            memset(recvBuf,0,5000);
            memset(sendBuf,0,5000);

            int ret = recv(clientSocket,recvBuf, 4999,0);
            if (ret < 0)
                break;      

            sprintf(sendBuf,"Hello %s ,message recved!\r\n",inet_ntoa(sockAddr.sin_addr));
            printf(sendBuf);
            ret = send(clientSocket,sendBuf, strlen(sendBuf),0);
            if (ret < 0)
                break;  
        }

        memset(sendBuf,0,5000);
        sprintf(sendBuf,"%s is Closed!\r\n",inet_ntoa(sockAddr.sin_addr));
        printf(sendBuf);
        closesocket(clientSocket);

    }
    closesocket(acceptSocket);
    WSACleanup();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值