详谈C++ socket网络编程实例(2)

时间:2022-06-01 12:46:29

功能

完成Cpp客户端简单功能,可收发数据。

Cpp服务端实例地址:【点击跳转

源码

?
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
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
//网络库文件
#include <winsock2.h>
//引入ws2_32.lib
#pragma comment(lib,"ws2_32.lib")
using std::cout;
using std::endl;
using std::cin;
int main()
{
    system("chcp 65001");
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        cout << "WSAStartUp error " << GetLastError() << endl;
        return 0;
    }
    //1、创建句柄
    SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    //2、连接服务端
    // connect(绑定的句柄, 服务端地址, 第二个参数的大小);
    SOCKADDR_IN ServerAddr;
    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(7890);
    ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//点分十进制转化为十进制
    if (SOCKET_ERROR == connect(clientSocket, (sockaddr *)&ServerAddr, sizeof(SOCKADDR_IN)))
    {
        cout << "连接失败" << endl;
        return 0;
    }
    //3、接收发送数据
    while (true)
    {
        char buffer[1024] = { 0 };
        scanf("%s", buffer);
        send(clientSocket, buffer, strlen(buffer), 0);
        int nRecv = recv(clientSocket, buffer, 1024, 0);
        if (nRecv <= 0)
        {
            break;
        }
        printf("[%d]接收数据, %s\n", nRecv, buffer);
    }
    printf("断开连接\n");
    //4、关闭句柄
    return 0;
}

效果

详谈C++ socket网络编程实例(2)

总结

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

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