Windows 下的最简单的TCP服务器客户端

他们是短连接的,服务器接受客户端之后,马上发送一个消息,发送完以后立即将客户端断开掉,然后继续等待下一个连接.


使用Winsocket2必须要引用到的头文件和需要包含到的链接库文件:

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



以下代码是Winsocket2的系统初始化和关闭的封装代码.

None.gif class WinSocketSystem
ExpandedBlockStart.gif {
InBlock.gifpublic:
InBlock.gif    WinSocketSystem()
ExpandedSubBlockStart.gif    {
InBlock.gif        int iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
InBlock.gif        if (iResult != NO_ERROR)
ExpandedSubBlockStart.gif        {
InBlock.gif            exit(-1);
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    ~WinSocketSystem()
ExpandedSubBlockStart.gif    {
InBlock.gif        WSACleanup();
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gifprotected:
InBlock.gif    WSADATA wsaData;
ExpandedBlockEnd.gif};
None.gif
None.gif static WinSocketSystem g_winsocketsystem;


服务器端代码:
None.gif class TCPServer
ExpandedBlockStart.gif {
InBlock.gifpublic:
InBlock.gif    TCPServer()
InBlock.gif        : mServerSocket(INVALID_SOCKET)
ExpandedSubBlockStart.gif    {
InBlock.gif        // 创建套接字
InBlock.gif
        mServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
InBlock.gif        if (mServerSocket == INVALID_SOCKET)
ExpandedSubBlockStart.gif        {
InBlock.gif            std::cout << "创建套接字失败!" << std::endl;
InBlock.gif            return;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        // 填充服务器的IP和端口号
InBlock.gif
        mServerAddr.sin_family        = AF_INET;
InBlock.gif        mServerAddr.sin_addr.s_addr    = INADDR_ANY;
InBlock.gif        mServerAddr.sin_port        = htons((u_short)SERVER_PORT);
InBlock.gif
InBlock.gif        // 绑定IP和端口
InBlock.gif
        if ( ::bind(mServerSocket, (sockaddr*)&mServerAddr, sizeof(mServerAddr)) == SOCKET_ERROR)
ExpandedSubBlockStart.gif        {
InBlock.gif            std::cout << "绑定IP和端口失败!" << std::endl;
InBlock.gif            return;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        // 监听客户端请求,最大同时连接数设置为10.
InBlock.gif
        if ( ::listen(mServerSocket, SOMAXCONN) == SOCKET_ERROR)
ExpandedSubBlockStart.gif        {
InBlock.gif            std::cout << "监听端口失败!" << std::endl;
InBlock.gif            return;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        std::cout << "启动TCP服务器成功!" << std::endl;
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    ~TCPServer()
ExpandedSubBlockStart.gif    {
InBlock.gif        ::closesocket(mServerSocket);
InBlock.gif        std::cout << "关闭TCP服务器成功!" << std::endl;
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    void run()
ExpandedSubBlockStart.gif    {
InBlock.gif        int nAcceptAddrLen = sizeof(mAcceptAddr);
InBlock.gif        for (;;)
ExpandedSubBlockStart.gif        {
InBlock.gif            // 以阻塞方式,等待接收客户端连接
InBlock.gif
            mAcceptSocket = ::accept(mServerSocket, (struct sockaddr*)&mAcceptAddr, &nAcceptAddrLen);
InBlock.gif            std::cout << "接受客户端IP:" << inet_ntoa(mAcceptAddr.sin_addr) << std::endl;
InBlock.gif
InBlock.gif            // 发送消息
InBlock.gif
            int ret = ::send(mAcceptSocket, SEND_STRING, (int)strlen(SEND_STRING), 0);
InBlock.gif            if (ret != 0)
ExpandedSubBlockStart.gif            {
InBlock.gif                std::cout << "发送消息成功!" << std::endl;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            // 关闭客户端套接字
InBlock.gif
            ::closesocket(mAcceptSocket);
InBlock.gif            std::cout << "断开客户端端成功!" << std::endl;
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gifprivate:
ExpandedSubBlockStart.gif    SOCKET        mServerSocket;    ///< 服务器套接字句柄
InBlock.gif
    sockaddr_in    mServerAddr;    ///< 服务器地址
ExpandedSubBlockEnd.gif

ExpandedSubBlockStart.gif    SOCKET        mAcceptSocket;    ///< 接受的客户端套接字句柄
InBlock.gif
    sockaddr_in    mAcceptAddr;    ///< 接收的客户端地址
ExpandedSubBlockEnd.gif
};
InBlock.gif
InBlock.gifint _tmain(int argc, _TCHAR* argv[])
ExpandedSubBlockStart.gif{
InBlock.gif    TCPServer server;
InBlock.gif    server.run();
InBlock.gif
InBlock.gif    return 0;
ExpandedSubBlockEnd.gif}


客户端代码:
None.gif class TCPClient
ExpandedBlockStart.gif {
InBlock.gifpublic:
InBlock.gif    TCPClient()
ExpandedSubBlockStart.gif    {
InBlock.gif        // 创建套接字
InBlock.gif
        mServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
InBlock.gif        if (mServerSocket == INVALID_SOCKET)
ExpandedSubBlockStart.gif        {
InBlock.gif            std::cout << "创建套接字失败!" << std::endl;
InBlock.gif            return;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        // 填充服务器的IP和端口号
InBlock.gif
        mServerAddr.sin_family        = AF_INET;
InBlock.gif        mServerAddr.sin_addr.s_addr    = inet_addr(SERVER_IP);
InBlock.gif        mServerAddr.sin_port        = htons((u_short)SERVER_PORT);
InBlock.gif
InBlock.gif        // 连接到服务器
InBlock.gif
        if ( ::connect(mServerSocket, (struct sockaddr*)&mServerAddr, sizeof(mServerAddr)))
ExpandedSubBlockStart.gif        {
InBlock.gif            ::closesocket(mServerSocket);
InBlock.gif            std::cout << "连接服务器失败!" << std::endl;
InBlock.gif            return;    
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    ~TCPClient()
ExpandedSubBlockStart.gif    {
InBlock.gif        ::closesocket(mServerSocket);
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gif    void run()
ExpandedSubBlockStart.gif    {
InBlock.gif        int nRecvSize = 0;
InBlock.gif        char buff[BUFFER_SIZE];
InBlock.gif        memset(buff, 0, sizeof(buff) );
InBlock.gif        while (nRecvSize = ::recv(mServerSocket, buff, BUFFER_SIZE, 0) )
ExpandedSubBlockStart.gif        {
InBlock.gif            if (mServerSocket == INVALID_SOCKET)
ExpandedSubBlockStart.gif            {                
InBlock.gif                break;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            std::cout << buff << std::endl;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        std::cout << "已经和服务器断开连接!" << std::endl;
ExpandedSubBlockEnd.gif    }
InBlock.gif
InBlock.gifprivate:
ExpandedSubBlockStart.gif    SOCKET        mServerSocket;    ///< 服务器套接字句柄
InBlock.gif
    sockaddr_in    mServerAddr;    ///< 服务器地址
ExpandedSubBlockEnd.gif
};
InBlock.gif
InBlock.gif
InBlock.gifint _tmain(int argc, _TCHAR* argv[])
ExpandedSubBlockStart.gif{
InBlock.gif    TCPClient client;
InBlock.gif    client.run();
InBlock.gif
InBlock.gif    system("pause");
InBlock.gif    return 0;
ExpandedSubBlockEnd.gif}
InBlock.gif
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值