详谈C++ socket网络编程实例

时间:2022-03-27 05:21:29

功能

实现基于sokcet的Cpp服务端

TIPS:功能包括接收客户端的数据,向客户端发送数据。

源码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
//#include <windows.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32")
using std::cout;
using std::endl;
using std::cin;
 
int main()
{
    system("chcp 65001");
    //SetConsoleOutputCP(65001);
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);//启动window动态网络库
    //1.创建socket
    //SOCKET == 句柄 == 文件描述符 == 套接字
    //socket(协议族类型,协议类型,0);
    //协议族类型 IPV4(AF_INET) IPV6
    //协议类型 TCP(SOCK_STREAM),UDP(SOCK_DROP)
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);//IPPROTO_TCP
    if (serverSocket == INVALID_SOCKET)
    {
        cout << "创建socket失败" << endl;
        return 0;
    }
    //2.绑定ip和端口号
    //127.0.0.1 永远指向本机
    //0.0.0.o 绑定所有网卡的ip
    SOCKADDR_IN serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(7890);//host to networks short,将主机字节序转化为网络字节序
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//点分十进制转换为10进制
    if (SOCKET_ERROR == bind(serverSocket, (sockaddr *)&serverAddr, sizeof(SOCKADDR_IN)))
    {
        cout << "bind 失败" << endl;
        return 0;
    }
    cout << "bind 成功" << endl;
    //3.监听,提示本机的操作系统
    if (INVALID_SOCKET == listen(serverSocket, 5))
    {
        cout << "listen 失败" << endl;
        return 0;
    }
    cout << "listen 成功" << endl;
    while(true)
    {
        //4.等待客户端连接
        SOCKADDR_IN clientAddr;
        int addrLen = sizeof(SOCKADDR_IN);
        SOCKET clientSocket = accept(serverSocket, (SOCKADDR *)&clientAddr, &addrLen);
        if (INVALID_SOCKET == clientSocket)
        {
            cout << "客户端连接失败 " << endl;
            return 0;
        }
        cout << "client ok " << inet_ntoa(clientAddr.sin_addr) << endl;
        cout << "port " << ntohs(clientAddr.sin_port) << endl;
        //5.收发数据
        //接收数据
        char recvBuffer[1024]{ 0 };
        int nRecv = recv(clientSocket, recvBuffer, 1024, 0);
        cout << "recvLen:" << nRecv << "内容:" << recvBuffer << endl;
        //发送数据
        int nSend = send(clientSocket, recvBuffer, nRecv, 0);
        cout << "send Len:" << nSend << endl;
        //6.关闭客户端
        closesocket(clientSocket);
    }
    //7.关闭服务端
    closesocket(serverSocket);
 
    WSACleanup();//卸载window动态网络库
    return 0;
}

效果

TIPS:利用sokit模拟工具模拟一个客户端终端。

详谈C++ socket网络编程实例

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/qq135595696/article/details/121076451