一个简单的TCP通信程序Demo

实现一个最简单的客户端和服务端的通信程序

服务器程序工作
1.初始化 Winsock库
2.创建监听套接字(socket()函数)
3.填写要绑定的本地地址结构(bind()函数)
4.给监听套接字绑定本地IP地址
5.开始监听(listen()函数)
6.循环执行 调用accept()函数接收客户端连接请求,如果accept()函数返回成功.则调用send()函数向客户端发送数据或者调用recv()函数从客户端接收数据

客户端程序工作
1.初始化 Winsock库
2.创建通信套接字(socket()函数)
3.填写要连接的服务器的地址结构
4.与服务器建立连接(connect()函数)
5.调用recv()函数接收服务器数据,send()函数发送数据给服务器

服务器程序代码:

// Server.cpp : Defines the entry point for the console application.
//

#include 
#include 
using namespace std;

#pragma comment(lib, "WS2_32.lib")
//表示链接WS2_32.lib这个库。
#define  PORT 1024

int main()
{
    SOCKET sock_server, newsock;
    struct sockaddr_in server_addr, client_addr; 
    char msg[] = { "Hello clinet" };
    // 初始化 winsock2.dll[12/27/2017 MagicScaring]
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);        //生成版本号
    if (WSAStartup(wVersionRequested, &wsaData) != 0)
    {
        cout << "加载 winsock.dll失败" << endl;
        return 0;
    }
    // 创建套接字 [12/27/2017 MagicScaring]
    if ((sock_server = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
    {
        cout << "创建套接字失败! 错误代码:" << WSAGetLastError() << endl;
        WSACleanup();                   //注销WinSock动态链接库
        return 0;
    }
    // 填写需要绑定的本地地址 [12/27/2017 MagicScaring]
    int addr_len = sizeof(struct sockaddr_in);
    memset((void*)&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(sock_server, (struct sockaddr*)&server_addr, addr_len) != 0)
    {
        cout << "绑定失败!错误代码:" << WSAGetLastError() << endl;
        closesocket(sock_server);               //关闭已连接套接字
        WSACleanup();                           //注销WinSock动态链接库
        return 0;
    }

    // 开始监听 [12/27/2017 MagicScaring]
    if (listen(sock_server, 0) != 0)
    {
        cout << "listen调用失败!错误代码:" << WSAGetLastError() << endl;
        closesocket(sock_server);
        WSACleanup();
        return 0;
    }
    else
    {
        cout << "listening...." << endl;
    }
    // 循环:接收连接请求并收发数据 [12/27/2017 MagicScaring]
    int size;
    while (true)
    {
        if ((newsock = accept(sock_server, (struct sockaddr *)&client_addr, &addr_len)) == INVALID_SOCKET)
        {
            cout << "accept 函数调用失败! 错误代码:" << WSAGetLastError() << endl;
            break;
        }
        else
        {
            cout << "成功接收到一个连接请求!" << endl;
            size = send(newsock, msg, sizeof(msg), 0);
            if (size == SOCKET_ERROR)
            {
                cout << "发送信息失败! 错误代码:" << WSAGetLastError() << endl;
                closesocket(newsock);
                continue;
            }
            else if (size == 0)
            {
                cout << "对方已关闭连接" << endl;
                closesocket(newsock);
                continue;
            }
            else
            {
                cout << "信息发送成功" << endl;
            }
            size = recv(newsock, msg, sizeof(msg), 0);
            if (size == SOCKET_ERROR)
            {
                cout << "接收信息失败! 错误代码:" << WSAGetLastError() << endl;
                closesocket(newsock);
                WSACleanup();
                return 0;
            }
            else if (size == 0)
            {
                cout << "对方已关闭连接" << endl;
                closesocket(newsock);
                WSACleanup();
                return 0;
            }
            else
            {
                cout << "The message from Client:" << msg << endl;

            }
        }
    }

    return 0;
}

客户端程序代码:

// Client.cpp : Defines the entry point for the console application.
//

#include 
#include 
using namespace std;

#pragma comment(lib, "WS2_32.lib")
//表示链接WS2_32.lib这个库。
#define  PORT 1024

int main()
{
    SOCKET sock_client;
    struct sockaddr_in server_addr;
    int addr_len = sizeof(struct sockaddr_in);
    char msgbuffer[1000];
    memset(msgbuffer, 0, sizeof(msgbuffer));
    // 初始化 winsock2.dll[12/27/2017 MagicScaring]
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 2);        //生成版本号
    if (WSAStartup(wVersionRequested, &wsaData) != 0)
    {
        cout << "加载 winsock.dll失败" << endl;
        return 0;
    }
    // 创建套接字 [12/27/2017 MagicScaring]
    if ((sock_client = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
    {
        cout << "创建套接字失败! 错误代码:" << WSAGetLastError() << endl;
        WSACleanup();                   //注销WinSock动态链接库
        return 0;
    }
    // 填写服务器地址 [12/27/2017 MagicScaring]
    char IP[20] = { "192.168.5.38" };
    /*char IP[20];
    cout << "输入服务器地址:" << endl;
    cin >> IP;*/
    memset((void*)&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr(IP);

    // 与服务器建立连接 [12/27/2017 MagicScaring]
    if (connect(sock_client, (struct sockaddr*)&server_addr, addr_len) == SOCKET_ERROR)
    {
        cout << "连接失败! 错误代码:" << WSAGetLastError() << endl;
        closesocket(sock_client);
        WSACleanup();
        return 0;
    }
    while (true)
    {
        int size;
        if ((size = recv(sock_client, msgbuffer, sizeof(msgbuffer), 0)) == SOCKET_ERROR)
        {
            cout << "接收信息失败! 错误代码:" << WSAGetLastError() << endl;
            closesocket(sock_client);
            WSACleanup();
            return 0;
        }
        else if (size == 0)
        {
            cout << "对方已关闭连接" << endl;
            closesocket(sock_client);
            WSACleanup();
            return 0;
        }
        else
        {
            cout << "The message from Server:" << msgbuffer << endl;
        }
        char send_msg[1000] = { "Hello server" };
        if((size = send(sock_client, send_msg, sizeof(send_msg),0)) == SOCKET_ERROR)
        {
            cout << "发送信息失败! 错误代码:" << WSAGetLastError() << endl;
        }
        else if (size == 0)
        {
            cout << "对方已关闭连接" << endl;
        }
        else
        {
            cout << "信息发送成功" << endl;
        }

    }
    closesocket(sock_client);
    WSACleanup();

    return 0;
}

服务器程序运行结果:
一个简单的TCP通信程序Demo_第1张图片

客户端程序运行结果:
一个简单的TCP通信程序Demo_第2张图片

你可能感兴趣的:(tcp-ip)